﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using System.Data;
using System.Data.SqlClient;
using Newtonsoft;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Trade.DBUtility;
using Trade.DBUtility.DataTableName;
using TradeWeb.Models;
using System.Web.Script.Serialization;
using System.IO;
using System.Dynamic;
using Newtonsoft.Json.Linq;
using System.Collections;
using System.Configuration;

namespace TradeWeb.Controllers
{
    public class ProcedureController : Controller
    {
        //
        // GET: /Procedure/

        public ActionResult Index()
        {
            return View();//Procedure
        }
        public string GetCodeInfo(string BarCode)
        {
            string jsonResult = string.Empty;
            //构造反馈对象
            dynamic damResult = new ExpandoObject();
            damResult.success = false;
            damResult.message = "获取失败";
            DataSet ds = new DataSet();
            string SQL = "select * from t_dispatch_serialno where OrderSerialID='" + BarCode + "' and isdel=0 and zzBG='已报工'";
            try
            {
                ds = CustomizableDesignBLL.GetData(SQL);
            }
            catch (Exception ex)
            {
                damResult.message = "获取信息报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            List<dynamic> varList = new List<dynamic>();
            if (ds.Tables[0].DefaultView.Count > 0)
            {
                foreach (DataRowView drv in ds.Tables[0].DefaultView)
                {
                    var item = Trade.DBUtility.ExtendObject.AutoMap(drv.Row);
                    varList.Add(item);
                }
                string docno = ds.Tables[0].DefaultView[0]["docno"].ToString();
                string sql = "select top 1 cperson,cpersonname,cdeptcode,cdeptname from T_dispatchlist where docno='" + docno + "'";
                try
                {
                    ds = CustomizableDesignBLL.GetData(sql);
                }
                catch (Exception ex)
                {
                    damResult.message = "获取人员信息报错：" + ex.Message;
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
                }
                string userInfo = ds.Tables[0].DefaultView[0][0].ToString() + "-" + ds.Tables[0].DefaultView[0][1].ToString();
                damResult.success = true;
                damResult.data = varList;
                damResult.bz = "(" + ds.Tables[0].DefaultView[0][2].ToString() + ")" + ds.Tables[0].DefaultView[0][3].ToString();
                damResult.message = userInfo;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            //jsonResult = "{\"success\":true  ,\"data\":" + JsonConvert.SerializeObject(varList) + "  ,\"message\":\"正常\"}";
            //
            jsonResult = "{\"success\":false   ,\"message\":\"此序列号不存在或者不是已报工状态\"}";
            return jsonResult;

        }
        public string GetCodeInfoCK(string BarCode)
        {
            string jsonResult = string.Empty;
            //构造反馈对象
            dynamic damResult = new ExpandoObject();
            damResult.success = false;
            damResult.message = "获取失败";
            DataSet ds = new DataSet();
            string sqlcheck = "select * from " + Common.GetdatabaseName("") + ".dbo.ST_SNDetail_SaleOut where cInvSN='" + BarCode + "'";
            try
            {
                ds = CustomizableDesignBLL.GetData(sqlcheck);
            }
            catch (Exception ex)
            {
                damResult.message = "获取信息报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            if (ds.Tables[0].DefaultView.Count > 0)
            {
                damResult.message = "此序列号已出库";
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            sqlcheck = "select * from " + Common.GetdatabaseName("") + ".dbo.ST_SNState with (nolock) where iSNState=9 and cInvSN='" + BarCode + "'";
            try
            {
                ds = CustomizableDesignBLL.GetData(sqlcheck);
            }
            catch (Exception ex)
            {
                damResult.message = "获取信息报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            if (ds.Tables[0].DefaultView.Count > 0)
            {
                damResult.message = "此序列号已出库";
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            sqlcheck = "select * from " + Common.GetdatabaseName("") + ".dbo.ST_SNState with (nolock) where iSNState=2 and cInvSN='" + BarCode + "'";
            try
            {
                ds = CustomizableDesignBLL.GetData(sqlcheck);
            }
            catch (Exception ex)
            {
                damResult.message = "获取信息报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            if (ds.Tables[0].DefaultView.Count == 0)
            {
                damResult.message = "此序列号未入库";
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            string SQL = "select a.*,b.cwhcode from t_dispatch_serialno a with (nolock) inner join " + Common.GetdatabaseName("") + ".dbo.ST_SNState b with (nolock) on a.OrderSerialID=b.cinvsn  where OrderSerialID='" + BarCode + "' and isdel=0";
            try
            {
                ds = CustomizableDesignBLL.GetData(SQL);
            }
            catch (Exception ex)
            {
                damResult.message = "获取信息报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            List<dynamic> varList = new List<dynamic>();
            if (ds.Tables[0].DefaultView.Count > 0)
            {
                DataSet ds2 = new DataSet();
                if (ds.Tables[0].DefaultView[0]["docno"].ToString() != string.Empty)
                {
                    sqlcheck = "select * from " + Common.GetdatabaseName("") + ".dbo.ST_SNDetail_PROIN where cInvSN='" + BarCode + "'";
                    try
                    {
                        ds2 = CustomizableDesignBLL.GetData(sqlcheck);
                    }
                    catch (Exception ex)
                    {
                        damResult.message = "获取信息报错：" + ex.Message;
                        jsonResult = JsonConvert.SerializeObject(damResult);
                        return jsonResult;
                    }
                    if (ds2.Tables[0].DefaultView.Count == 0)
                    {
                        damResult.message = "此序列号未入库";
                        jsonResult = JsonConvert.SerializeObject(damResult);
                        return jsonResult;
                    }
                }
                else
                {
                    sqlcheck = "select 1 from " + Common.GetdatabaseName("") + ".dbo.ST_SNDetail_PuIN where cInvSN='" + BarCode + "'union all  select 1 from " + Common.GetdatabaseName("") + ".dbo.ST_SNDetail_QC where cInvSN='" + BarCode + "' union all  select 1 from " + Common.GetdatabaseName("") + ".dbo.ST_SNDetail_OtherIN  where cInvSN='" + BarCode + "'";
                    try
                    {
                        ds2 = CustomizableDesignBLL.GetData(sqlcheck);
                    }
                    catch (Exception ex)
                    {
                        damResult.message = "获取信息报错：" + ex.Message;
                        jsonResult = JsonConvert.SerializeObject(damResult);
                        return jsonResult;
                    }
                    if (ds2.Tables[0].DefaultView.Count == 0)
                    {
                        damResult.message = "此序列号未入库";
                        jsonResult = JsonConvert.SerializeObject(damResult);
                        return jsonResult;
                    }
                }
                foreach (DataRowView drv in ds.Tables[0].DefaultView)
                {
                    var item = Trade.DBUtility.ExtendObject.AutoMap(drv.Row);
                    varList.Add(item);
                }
                string docno = ds.Tables[0].DefaultView[0]["docno"].ToString();
                string sql = "select top 1 cperson,cpersonname,cdeptcode,cdeptname from T_dispatchlist where docno='" + docno + "'";
                try
                {
                    ds = CustomizableDesignBLL.GetData(sql);
                }
                catch (Exception ex)
                {
                    damResult.message = "获取人员信息报错：" + ex.Message;
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
                }
                string userInfo = "";
                try
                {
                    userInfo = ds.Tables[0].DefaultView[0][0].ToString() + "-" + ds.Tables[0].DefaultView[0][1].ToString();
                }
                catch (Exception)
                {
                }

                damResult.success = true;
                damResult.data = varList;
                //damResult.bz = "(" + ds.Tables[0].DefaultView[0][2].ToString() + ")" + ds.Tables[0].DefaultView[0][3].ToString();
                damResult.message = userInfo;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            //jsonResult = "{\"success\":true  ,\"data\":" + JsonConvert.SerializeObject(varList) + "  ,\"message\":\"正常\"}";
            //
            jsonResult = "{\"success\":false   ,\"message\":\"此序列号不存在或者未入库！\"}";
            return jsonResult;

        }
        public string GetCodeInfoJH(string BarCode)
        {
            string jsonResult = string.Empty;
            //构造反馈对象
            dynamic damResult = new ExpandoObject();
            damResult.success = false;
            damResult.message = "获取失败";
            DataSet ds = new DataSet();
            string sqlcheck = "select * from T_jhuo_b where XLCode='" + BarCode + "'";
            try
            {
                ds = CustomizableDesignBLL.GetData(sqlcheck);
            }
            catch (Exception ex)
            {
                damResult.message = "获取拣货信息报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            if (ds.Tables[0].DefaultView.Count > 0)
            {
                damResult.message = "此序列号已拣货";
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }

            sqlcheck = "select * from " + Common.GetdatabaseName("") + ".dbo.ST_SNDetail_SaleOut where cInvSN='" + BarCode + "'";
            try
            {
                ds = CustomizableDesignBLL.GetData(sqlcheck);
            }
            catch (Exception ex)
            {
                damResult.message = "获取信息报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            if (ds.Tables[0].DefaultView.Count > 0)
            {
                damResult.message = "此序列号已出库";
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            sqlcheck = "select * from " + Common.GetdatabaseName("") + ".dbo.ST_SNState  with (nolock) where iSNState=9 and cInvSN='" + BarCode + "'";
            try
            {
                ds = CustomizableDesignBLL.GetData(sqlcheck);
            }
            catch (Exception ex)
            {
                damResult.message = "获取信息报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            if (ds.Tables[0].DefaultView.Count > 0)
            {
                damResult.message = "此序列号已出库";
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            sqlcheck = "select * from " + Common.GetdatabaseName("") + ".dbo.ST_SNState with (nolock) where iSNState=2 and cInvSN='" + BarCode + "'";
            try
            {
                ds = CustomizableDesignBLL.GetData(sqlcheck);
            }
            catch (Exception ex)
            {
                damResult.message = "获取信息报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            if (ds.Tables[0].DefaultView.Count == 0)
            {
                damResult.message = "此序列号未入库";
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            string SQL = "select a.*,b.cwhcode,c.cwhname from t_dispatch_serialno a with (nolock) inner join " + Common.GetdatabaseName("") + ".dbo.ST_SNState b with (nolock) on a.OrderSerialID=b.cinvsn inner join " + Common.GetdatabaseName("") + ".dbo.warehouse c with (nolock) on b.cwhcode=c.cwhcode  where OrderSerialID='" + BarCode + "' and isdel=0";
            try
            {
                ds = CustomizableDesignBLL.GetData(SQL);
            }
            catch (Exception ex)
            {
                damResult.message = "获取信息报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            List<dynamic> varList = new List<dynamic>();
            if (ds.Tables[0].DefaultView.Count > 0)
            {
                DataSet ds2 = new DataSet();
                if (ds.Tables[0].DefaultView[0]["docno"].ToString() != string.Empty)
                {
                    sqlcheck = "select * from " + Common.GetdatabaseName("") + ".dbo.ST_SNDetail_PROIN where cInvSN='" + BarCode + "'";
                    try
                    {
                        ds2 = CustomizableDesignBLL.GetData(sqlcheck);
                    }
                    catch (Exception ex)
                    {
                        damResult.message = "获取信息报错：" + ex.Message;
                        jsonResult = JsonConvert.SerializeObject(damResult);
                        return jsonResult;
                    }
                    if (ds2.Tables[0].DefaultView.Count == 0)
                    {
                        damResult.message = "此序列号未入库";
                        jsonResult = JsonConvert.SerializeObject(damResult);
                        return jsonResult;
                    }
                }
                else
                {
                    sqlcheck = "select 1 from " + Common.GetdatabaseName("") + ".dbo.ST_SNDetail_PuIN where cInvSN='" + BarCode + "'union all  select 1 from " + Common.GetdatabaseName("") + ".dbo.ST_SNDetail_QC where cInvSN='" + BarCode + "' union all  select 1 from " + Common.GetdatabaseName("") + ".dbo.ST_SNDetail_OtherIN  where cInvSN='" + BarCode + "'";
                    try
                    {
                        ds2 = CustomizableDesignBLL.GetData(sqlcheck);
                    }
                    catch (Exception ex)
                    {
                        damResult.message = "获取信息报错：" + ex.Message;
                        jsonResult = JsonConvert.SerializeObject(damResult);
                        return jsonResult;
                    }
                    if (ds2.Tables[0].DefaultView.Count == 0)
                    {
                        damResult.message = "此序列号未入库";
                        jsonResult = JsonConvert.SerializeObject(damResult);
                        return jsonResult;
                    }
                }
                foreach (DataRowView drv in ds.Tables[0].DefaultView)
                {
                    var item = Trade.DBUtility.ExtendObject.AutoMap(drv.Row);
                    varList.Add(item);
                }
                string docno = ds.Tables[0].DefaultView[0]["docno"].ToString();
                string sql = "select top 1 cperson,cpersonname,cdeptcode,cdeptname from T_dispatchlist where docno='" + docno + "'";
                try
                {
                    ds = CustomizableDesignBLL.GetData(sql);
                }
                catch (Exception ex)
                {
                    damResult.message = "获取人员信息报错：" + ex.Message;
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
                }
                string userInfo = "";
                string bz = "";
                if (ds.Tables[0].DefaultView.Count > 0)
                {
                    try
                    {
                        userInfo = ds.Tables[0].DefaultView[0][0].ToString() + "-" + ds.Tables[0].DefaultView[0][1].ToString();
                        bz = "(" + ds.Tables[0].DefaultView[0][2].ToString() + ")" + ds.Tables[0].DefaultView[0][3].ToString();

                    }
                    catch (Exception)
                    {
                    }
                }

                damResult.success = true;
                damResult.data = varList;
                damResult.message = userInfo;
                damResult.bz = bz;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            //jsonResult = "{\"success\":true  ,\"data\":" + JsonConvert.SerializeObject(varList) + "  ,\"message\":\"正常\"}";
            //
            jsonResult = "{\"success\":false   ,\"message\":\"此序列号不存在或者未入库！\"}";
            return jsonResult;

        }
        public string ProceJH(string MasterData, string DetailData)
        {
            string jsonResult = string.Empty;
            //构造反馈对象
            dynamic damResult = new ExpandoObject();
            damResult.success = false;
            damResult.message = "获取失败";
            string strPKValue = "";
            //测试直接JSON转换数据集的 这个是可以做的，但是不是需要现在做的。因为这个是整个框架都要改了。没那个时间
            //DataSet dstest = JsonConvert.DeserializeObject<DataSet>(strDsData);
            string strTableName = "t_jhuo";
            string strTableDetail = strTableName + "_b";
            //是否新增
            bool bisAdd = false;
            //先获取数据库数据，如果没有数据就新增
            List<DataTableName> dtnGetDataList = new List<DataTableName>();
            DataSet dsGetData = new DataSet();
            DataTableName dtnGetData = new DataTableName();
            dtnGetData.strSelectSQL = "Select * from " + strTableName + " where 1=0";
            dtnGetData.strTableName = strTableName;
            dtnGetDataList.Add(dtnGetData);
            //
            dtnGetData = new DataTableName();
            dtnGetData.strSelectSQL = "Select * from " + strTableDetail + " where 1=0 ";
            dtnGetData.strTableName = strTableDetail;
            dtnGetDataList.Add(dtnGetData);
            //
            try
            {
                dsGetData = CustomizableDesignBLL.GetData(dtnGetDataList, true);
            }
            catch (Exception ex)
            {
                damResult.message = "获取模块数据表结构失败:" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            if (dsGetData.Tables[strTableName].DefaultView.Count == 0)
            {
                dsGetData.Tables[strTableName].Rows.Add(dsGetData.Tables[0].NewRow());
                bisAdd = true;
            }
            //
            #region 主表部分
            JavaScriptSerializer Serializer = new JavaScriptSerializer();
            List<DataSave> ListDsData = Serializer.Deserialize<List<DataSave>>(MasterData);
            for (int i = 0; i < ListDsData.Count; i++)
            {
                DataSave dtmtsave = ListDsData[i];
                if (dsGetData.Tables[dtmtsave.TableName].Columns.Contains(dtmtsave.CoulumName))
                {


                    if (dsGetData.Tables[dtmtsave.TableName].Columns[dtmtsave.CoulumName].DataType.Name == "Boolean")
                    {
                        string strValue = dtmtsave.CoulunValue;


                        bool bisValue = false;
                        if (Boolean.TryParse(strValue, out bisValue))
                            dsGetData.Tables[dtmtsave.TableName].DefaultView[0][dtmtsave.CoulumName] = bisValue;
                        else
                        {
                            if (strValue.ToString().ToLower() == "true" || strValue.ToString().ToLower() == "1")
                                dsGetData.Tables[dtmtsave.TableName].DefaultView[0][dtmtsave.CoulumName] = true;
                            else
                                dsGetData.Tables[dtmtsave.TableName].DefaultView[0][dtmtsave.CoulumName] = false;
                        }
                    }
                    else
                    {
                        if (!dsGetData.Tables[dtmtsave.TableName].Columns[dtmtsave.CoulumName].ReadOnly)
                            dsGetData.Tables[dtmtsave.TableName].DefaultView[0][dtmtsave.CoulumName] = dtmtsave.CoulunValue;
                        //
                    }
                }
            }
            //一些必输项自动赋值
            strPKValue = "JH" + DateTime.Now.ToString("yyyyMMdd") + GetMaxLs("JH" + DateTime.Now.ToString("yyyyMMdd"), strTableName, "SerialNum", 4).ToString("0000");
            if (dsGetData.Tables[strTableName].Columns.Contains("SaveTime"))
                dsGetData.Tables[strTableName].DefaultView[0]["SaveTime"] = DateTime.Now.ToString();
            dsGetData.Tables[strTableName].DefaultView[0]["SerialNum"] = strPKValue;
            dsGetData.Tables[strTableName].DefaultView[0]["State"] = 0;
            dsGetData.Tables[strTableName].DefaultView[0]["ISDel"] = 0;
            dsGetData.Tables[strTableName].DefaultView[0].EndEdit();
            #endregion
            #region 细表部分
            // 先删除细表数据
            while (dsGetData.Tables[strTableDetail].DefaultView.Count > 0)
                dsGetData.Tables[strTableDetail].DefaultView[0].Delete();
            JavaScriptSerializer SerializerDetail = new JavaScriptSerializer();
            dynamic ListDsDataDetail = Serializer.Deserialize<dynamic>(DetailData);
            for (int i = 0; i < ListDsDataDetail.Length; i++)
            {
                DataRow drDetailNew = dsGetData.Tables[strTableDetail].NewRow();
                dynamic dtmtsavelist = ListDsDataDetail[i];
                foreach (dynamic dsv in dtmtsavelist)
                {
                    String strDetaliTablename = string.Empty;
                    String strDetaliCoulumName = string.Empty;
                    String strDetaliCoulunValue = string.Empty;
                    foreach (string strkey in dsv.Keys)
                    {
                        if (strkey == "TableName")
                            strDetaliTablename = dsv[strkey].ToString();
                        if (strkey == "CoulumName")
                            strDetaliCoulumName = dsv[strkey].ToString();
                        if (strkey == "CoulunValue")
                            strDetaliCoulunValue = dsv[strkey].ToString();
                    }
                    //
                    if (!dsGetData.Tables[strDetaliTablename].Columns.Contains(strDetaliCoulumName))
                        continue;
                    //
                    if (!dsGetData.Tables[strDetaliTablename].Columns[strDetaliCoulumName].ReadOnly && strDetaliCoulumName != "SortID" && strDetaliCoulumName != "ISDel")
                    {
                        if (dsGetData.Tables[strDetaliTablename].Columns.Contains(strDetaliCoulumName))
                        {
                            if (strDetaliCoulunValue == null || strDetaliCoulunValue == string.Empty)
                                continue;
                            if (dsGetData.Tables[strDetaliTablename].Columns[strDetaliCoulumName].DataType.Name == "Int32")
                            {
                                decimal dec = Convert.ToDecimal(strDetaliCoulunValue);
                                drDetailNew[strDetaliCoulumName] = Convert.ToInt32(dec);
                            }
                            else
                            {
                                drDetailNew[strDetaliCoulumName] = strDetaliCoulunValue;
                            }
                        }
                    }
                }
                //赋值一些必要的值
                drDetailNew["SerialNum"] = strPKValue;
                drDetailNew["State"] = 0;
                drDetailNew["ISDel"] = 0;
                dsGetData.Tables[strTableDetail].Rows.Add(drDetailNew);
            }
            #endregion
            try
            {
                CustomizableDesignBLL.SaveData(dsGetData, dtnGetDataList);
            }
            catch (Exception ex)
            {
                damResult.message = "保存模块数据报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            DataSet ds = dsGetData.Copy();
            string xlhList = "";
            for (int i = 0; i < ds.Tables[1].DefaultView.Count; i++)
            {
                if (i > 0) xlhList += ",";
                xlhList += "'" + ds.Tables[1].DefaultView[i]["XLCode"].ToString() + "'";
            }
            string sql = "update T_dispatch_serialno set zzBG='已拣货' where OrderSerialID in(" + xlhList + ")";
            try
            {
                CustomizableDesignBLL.ExecSQL(sql);
            }
            catch (Exception ex)
            {
                damResult.message = "回刷数据失败：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            damResult.success = true;
            damResult.message = strPKValue;
            jsonResult = JsonConvert.SerializeObject(damResult);
            return jsonResult;
        }

        public string GetCodeInfoBG(string BarCode)
        {
            string jsonResult = string.Empty;
            //构造反馈对象
            dynamic damResult = new ExpandoObject();
            damResult.success = false;
            damResult.message = "获取失败";
            DataSet ds = new DataSet();
            string sqlcheck = "select * from T_GXbgDetail where XLCode='" + BarCode + "'";
            try
            {
                ds = CustomizableDesignBLL.GetData(sqlcheck);
            }
            catch (Exception ex)
            {
                damResult.message = "获取报工信息报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            if (ds.Tables[0].DefaultView.Count > 0)
            {
                damResult.message = "此序列号已报工";
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            string SQL = "select * from " + Common.GetdatabaseName("") + ".dbo.ST_SNDetail_proin where cInvSN='" + BarCode + "'";
            DataSet ddss = new DataSet();
            try
            {
                ddss = CustomizableDesignBLL.GetData(SQL);
            }
            catch (Exception ex)
            {
                damResult.message = "获取信息报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            if (ddss.Tables[0].DefaultView.Count > 0)
            {
                damResult.message = "此序列号已入库";
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;

            }
            SQL = "select * from t_dispatch_serialno where OrderSerialID='" + BarCode + "' and isdel=0";
            try
            {
                ds = CustomizableDesignBLL.GetData(SQL);
            }
            catch (Exception ex)
            {
                damResult.message = "获取信息报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            List<dynamic> varList = new List<dynamic>();
            if (ds.Tables[0].DefaultView.Count > 0)
            {
                foreach (DataRowView drv in ds.Tables[0].DefaultView)
                {
                    var item = Trade.DBUtility.ExtendObject.AutoMap(drv.Row);
                    varList.Add(item);
                }
                string docno = ds.Tables[0].DefaultView[0]["docno"].ToString();
                string sql = "select top 1 cperson,cpersonname,cdeptcode,cdeptname from T_dispatchlist where docno='" + docno + "'";
                try
                {
                    ds = CustomizableDesignBLL.GetData(sql);
                }
                catch (Exception ex)
                {
                    damResult.message = "获取人员信息报错：" + ex.Message;
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
                }
                string userInfo = ds.Tables[0].DefaultView[0][0].ToString() + "-" + ds.Tables[0].DefaultView[0][1].ToString();
                damResult.success = true;
                damResult.data = varList;
                damResult.bz = "(" + ds.Tables[0].DefaultView[0][2].ToString() + ")" + ds.Tables[0].DefaultView[0][3].ToString();
                damResult.message = userInfo;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            //jsonResult = "{\"success\":true  ,\"data\":" + JsonConvert.SerializeObject(varList) + "  ,\"message\":\"正常\"}";
            //
            jsonResult = "{\"success\":false   ,\"message\":\"此序列号不存在！\"}";
            return jsonResult;

        }
        public string ProceBG(string MasterData, string DetailData)
        {
            string jsonResult = string.Empty;
            //构造反馈对象
            dynamic damResult = new ExpandoObject();
            damResult.success = false;
            damResult.message = "获取失败";
            string strPKValue = "";
            //测试直接JSON转换数据集的 这个是可以做的，但是不是需要现在做的。因为这个是整个框架都要改了。没那个时间
            //DataSet dstest = JsonConvert.DeserializeObject<DataSet>(strDsData);
            string strTableName = "T_GXbg";
            string strTableDetail = strTableName + "Detail";
            //是否新增
            bool bisAdd = false;
            //先获取数据库数据，如果没有数据就新增
            List<DataTableName> dtnGetDataList = new List<DataTableName>();
            DataSet dsGetData = new DataSet();
            DataTableName dtnGetData = new DataTableName();
            dtnGetData.strSelectSQL = "Select * from " + strTableName + " where 1=0";
            dtnGetData.strTableName = strTableName;
            dtnGetDataList.Add(dtnGetData);
            //
            dtnGetData = new DataTableName();
            dtnGetData.strSelectSQL = "Select * from " + strTableDetail + " where 1=0 ";
            dtnGetData.strTableName = strTableDetail;
            dtnGetDataList.Add(dtnGetData);
            //
            try
            {
                dsGetData = CustomizableDesignBLL.GetData(dtnGetDataList, true);
            }
            catch (Exception ex)
            {
                damResult.message = "获取模块数据表结构失败:" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            if (dsGetData.Tables[strTableName].DefaultView.Count == 0)
            {
                dsGetData.Tables[strTableName].Rows.Add(dsGetData.Tables[0].NewRow());
                bisAdd = true;
            }
            //
            #region 主表部分
            JavaScriptSerializer Serializer = new JavaScriptSerializer();
            List<DataSave> ListDsData = Serializer.Deserialize<List<DataSave>>(MasterData);
            for (int i = 0; i < ListDsData.Count; i++)
            {
                DataSave dtmtsave = ListDsData[i];
                if (dsGetData.Tables[dtmtsave.TableName].Columns.Contains(dtmtsave.CoulumName))
                {


                    if (dsGetData.Tables[dtmtsave.TableName].Columns[dtmtsave.CoulumName].DataType.Name == "Boolean")
                    {
                        string strValue = dtmtsave.CoulunValue;


                        bool bisValue = false;
                        if (Boolean.TryParse(strValue, out bisValue))
                            dsGetData.Tables[dtmtsave.TableName].DefaultView[0][dtmtsave.CoulumName] = bisValue;
                        else
                        {
                            if (strValue.ToString().ToLower() == "true" || strValue.ToString().ToLower() == "1")
                                dsGetData.Tables[dtmtsave.TableName].DefaultView[0][dtmtsave.CoulumName] = true;
                            else
                                dsGetData.Tables[dtmtsave.TableName].DefaultView[0][dtmtsave.CoulumName] = false;
                        }
                    }
                    else
                    {
                        if (!dsGetData.Tables[dtmtsave.TableName].Columns[dtmtsave.CoulumName].ReadOnly)
                            dsGetData.Tables[dtmtsave.TableName].DefaultView[0][dtmtsave.CoulumName] = dtmtsave.CoulunValue;
                        //
                    }
                }
            }
            //一些必输项自动赋值
            strPKValue = DateTime.Now.ToString("yyyyMMdd") + GetMaxLs(DateTime.Now.ToString("yyyyMMdd"), strTableName, "SerialNum", 4).ToString("0000");
            if (dsGetData.Tables[strTableName].Columns.Contains("SaveTime"))
                dsGetData.Tables[strTableName].DefaultView[0]["SaveTime"] = DateTime.Now.ToString();
            dsGetData.Tables[strTableName].DefaultView[0]["SerialNum"] = strPKValue;
            dsGetData.Tables[strTableName].DefaultView[0]["State"] = 0;
            dsGetData.Tables[strTableName].DefaultView[0]["ISDel"] = 0;
            dsGetData.Tables[strTableName].DefaultView[0].EndEdit();
            #endregion
            #region 细表部分
            // 先删除细表数据
            while (dsGetData.Tables[strTableDetail].DefaultView.Count > 0)
                dsGetData.Tables[strTableDetail].DefaultView[0].Delete();
            JavaScriptSerializer SerializerDetail = new JavaScriptSerializer();
            dynamic ListDsDataDetail = Serializer.Deserialize<dynamic>(DetailData);
            for (int i = 0; i < ListDsDataDetail.Length; i++)
            {
                DataRow drDetailNew = dsGetData.Tables[strTableDetail].NewRow();
                dynamic dtmtsavelist = ListDsDataDetail[i];
                foreach (dynamic dsv in dtmtsavelist)
                {
                    String strDetaliTablename = string.Empty;
                    String strDetaliCoulumName = string.Empty;
                    String strDetaliCoulunValue = string.Empty;
                    foreach (string strkey in dsv.Keys)
                    {
                        if (strkey == "TableName")
                            strDetaliTablename = dsv[strkey].ToString();
                        if (strkey == "CoulumName")
                            strDetaliCoulumName = dsv[strkey].ToString();
                        if (strkey == "CoulunValue")
                            strDetaliCoulunValue = dsv[strkey].ToString();
                    }
                    //
                    if (!dsGetData.Tables[strDetaliTablename].Columns.Contains(strDetaliCoulumName))
                        continue;
                    //
                    if (!dsGetData.Tables[strDetaliTablename].Columns[strDetaliCoulumName].ReadOnly && strDetaliCoulumName != "SortID" && strDetaliCoulumName != "ISDel")
                    {
                        if (dsGetData.Tables[strDetaliTablename].Columns.Contains(strDetaliCoulumName))
                        {
                            if (strDetaliCoulunValue == null || strDetaliCoulunValue == string.Empty)
                                continue;
                            if (dsGetData.Tables[strDetaliTablename].Columns[strDetaliCoulumName].DataType.Name == "Int32")
                            {
                                decimal dec = Convert.ToDecimal(strDetaliCoulunValue);
                                drDetailNew[strDetaliCoulumName] = Convert.ToInt32(dec);
                            }
                            else
                            {
                                drDetailNew[strDetaliCoulumName] = strDetaliCoulunValue;
                            }
                        }
                    }
                }
                //赋值一些必要的值
                drDetailNew["SerialNum"] = strPKValue;
                drDetailNew["State"] = 0;
                drDetailNew["ISDel"] = 0;
                dsGetData.Tables[strTableDetail].Rows.Add(drDetailNew);
            }
            #endregion
            try
            {
                CustomizableDesignBLL.SaveData(dsGetData, dtnGetDataList);
            }
            catch (Exception ex)
            {
                damResult.message = "保存模块数据报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            DataSet ds = dsGetData.Copy();
            string xlhList = "";
            for (int i = 0; i < ds.Tables[1].DefaultView.Count; i++)
            {
                if (i > 0) xlhList += ",";
                xlhList += "'" + ds.Tables[1].DefaultView[i]["XLCode"].ToString() + "'";
            }
            string sql = "update T_dispatch_serialno set zzBG='已报工' where OrderSerialID in(" + xlhList + ")";
            try
            {
                CustomizableDesignBLL.ExecSQL(sql);
            }
            catch (Exception ex)
            {
                damResult.message = "回刷数据失败：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            damResult.success = true;
            damResult.message = strPKValue;
            jsonResult = JsonConvert.SerializeObject(damResult);
            return jsonResult;
        }
        public string delete(string SerialNum)
        {
            string jsonResult = string.Empty;
            //构造反馈对象
            dynamic damResult = new ExpandoObject();
            damResult.success = false;
            damResult.message = "获取失败";
            List<string> strList = new List<string>();
            strList.Add("delete from T_GXbg where SerialNum='" + SerialNum + "'");
            strList.Add("delete from T_GXbgDetail where SerialNum='" + SerialNum + "'");
            try
            {
                CustomizableDesignBLL.ExecSQL(strList);
            }
            catch (Exception ex)
            {
                damResult.message = "删除数据失败：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            damResult.success = true;
            damResult.message = "";
            jsonResult = JsonConvert.SerializeObject(damResult);
            return jsonResult;
        }
        public string SaveIn(string strPKValue, string UserID, string Pwd, string swList)
        {
            string jsonResult = string.Empty;
            //构造反馈对象
            dynamic damResult = new ExpandoObject();
            damResult.success = false;
            damResult.message = "获取失败";
            string strTableName = "T_GXbg";
            string strTableDetail = "T_GXbgDetail";
            string strPKValues = "";
            #region 重新获取数据
            DataSet ds = new DataSet();
            List<DataTableName> dtnList = new List<DataTableName>();
            DataTableName dtn = new DataTableName();
            dtn.strSelectSQL = "Select * from " + strTableName + " where SerialNum= '" + strPKValue + "'";
            dtn.strTableName = strTableName;
            dtnList.Add(dtn);
            dtn = new DataTableName();
            if (swList != "")
                dtn.strSelectSQL = "Select * from " + strTableDetail + " where  XLCode in(" + swList + ")";
            else
            {
                damResult.message = "请扫描数据!";
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            //   dtn.strSelectSQL = "Select * from " + strTableDetail + " where SerialNum= '" + strPKValue + "'";
            dtn.strTableName = strTableDetail;
            dtnList.Add(dtn);
            try
            {
                ds = CustomizableDesignBLL.GetData(dtnList, false);
            }
            catch (Exception ex)
            {
                damResult.message = "获取保存后数据报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            #endregion

            string strConn = ConfigurationManager.ConnectionStrings["ConStr1"].ConnectionString;
            ADODB.Connection oCon = new ADODB.Connection();
            string strZ8DataBase = ConfigurationManager.AppSettings["Z8DataBase"];
            if (strZ8DataBase == null || strZ8DataBase == "")
            {
                damResult.message = "Z8DataBase没有设置";
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            string strYongYouDBName = Common.GetdatabaseName("");
            string strZT = strYongYouDBName.Substring(7, 3);
            string sAccID = strZT;
            string sYear = DateTime.Now.Year.ToString();
            string strUserCode = UserID;
            string strUserPwd = Pwd;
            //if (string.IsNullOrEmpty(strUserCode))
            //{
                strUserCode = "sxc";
                strUserPwd = "637813";

                //damResult.message = "strUserCode没有设置";
                //jsonResult = JsonConvert.SerializeObject(damResult);
                //return jsonResult;
            //}

            string sDate = DateTime.Now.ToString("yyyy-MM-dd");
            string sServer = Common.getU8SerVerIP();// "172.16.1.20";// strServerIP; 
            //if (Common.getBisTest())
            //{
            //    sDate = new DateTime(2019, 2, 28).ToString("yyyy-MM-dd");
            //}
            //
            //合并中间表
            #region 合并相同存货的数量
            ds.Tables[1].DefaultView.Sort = "MoDID";
            DataSet dsff = ds.Clone();
            int len = ds.Tables[1].DefaultView.Count;
            decimal qty = 0;
            string Modid = "";
            bool flag = false;
            for (int i = 0; i < len; )
            {
                flag = true;
                bool xx = false;//是否进入以下循环
                qty = decimal.Parse(ds.Tables[1].DefaultView[i]["qty"].ToString()); ;
                Modid = ds.Tables[1].DefaultView[i]["Modid"].ToString();
                for (int j = i + 1; j < len; j++)
                {
                    xx = true;
                    if (Modid == ds.Tables[1].DefaultView[j]["Modid"].ToString())
                    {
                        qty += 1;
                        ds.Tables[1].DefaultView[j]["qty"] = qty;
                        i = j;
                    }
                    else
                    {
                        flag = false;
                        ds.Tables[1].DefaultView[i]["qty"] = qty;
                        ds.Tables[1].DefaultView[i].EndEdit();
                        dsff.Tables[1].Rows.Add(ds.Tables[1].DefaultView[i].Row.ItemArray);
                        i = j;
                        break;
                    }

                }
                if (!xx) i++;
            }
            if (flag)
            {
                ds.Tables[1].DefaultView[len - 1]["qty"] = qty;
                ds.Tables[1].DefaultView[len - 1].EndEdit();
                dsff.Tables[1].Rows.Add(ds.Tables[1].DefaultView[len - 1].Row.ItemArray);
            }
            dsff.Tables[0].Rows.Add(ds.Tables[0].DefaultView[0].Row.ItemArray);
            for (int w = 0; w < dsff.Tables[1].DefaultView.Count; w++)
            {
                if (strPKValues != "") strPKValues += ",";
                strPKValues += "'" + dsff.Tables[1].DefaultView[w]["SerialID"].ToString() + "'";
            }
            #endregion

            //检验是否已生成入库单
            string sqlcin = "select * from " + strYongYouDBName + ".dbo.rdrecord10 where cdefine10='" + dsff.Tables[1].DefaultView[0]["SerialID"].ToString() + "'";
            try
            {
                DataSet sqlds = CustomizableDesignBLL.GetData(sqlcin);
                if (sqlds.Tables[0].DefaultView.Count > 0)
                {
                    damResult.message = "已经生成此单据的入库单,请前往U8处理,单号为" + sqlds.Tables[0].DefaultView[0]["cCode"].ToString();
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
                }
            }
            catch (Exception ex)
            {
                damResult.message = "sql有误" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            try
            {
                oCon.CursorLocation = ADODB.CursorLocationEnum.adUseClient;
                oCon.ConnectionString = strConn;
                oCon.Open(strConn, "", "", -1);
                //开始事务，很关键
                //oCon.BeginTrans();
                //因为要排序，所以传了ds.Copy()
                string strMsg = new YYAPI.coapi().ToYYCCPRK(oCon, dsff.Copy(), strYongYouDBName, strZT, sYear, strUserCode, strUserPwd, sDate, sServer, strPKValue);
                if (!string.IsNullOrEmpty(strMsg))
                {
                    oCon.RollbackTrans();
                    damResult.message = "调用产成品入库API错误：" + strMsg;
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
                }

                ADODB.Recordset rsRecord = new ADODB.Recordset();
                string strRsSQLRecord = "select (select top 1 cWhCode from rdrecord10 where id=rdrecords10.id) cWhCode,(select top 1 convert(nchar,convert(money,ufts),2) from rdrecord10 where id=rdrecords10.id) utfs1,* from rdrecords10 where cdefine25 in(" + strPKValues + ")";
                rsRecord.Open(strRsSQLRecord, oCon, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockOptimistic, (int)ADODB.CommandTypeEnum.adCmdText);
                object objADO = null;
                int iOptions = 0;
                if (rsRecord.RecordCount == 0)
                {
                    //oCon.RollbackTrans();
                    damResult.message = "出库记录为空！";
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
                }
                string strID = rsRecord.Fields["id"].Value.ToString();
                string strutfs1 = rsRecord.Fields["utfs1"].Value.ToString();
                for (int i = 0; i < rsRecord.RecordCount; i++)
                {
                    int x = 1;
                    for (int j = 0; j < ds.Tables[1].DefaultView.Count; j++)
                    {
                        if (rsRecord.Fields["impoids"].Value.ToString() == ds.Tables[1].DefaultView[j]["MoDID"].ToString())
                        {
                            string ivouchsID = rsRecord.Fields["AutoID"].Value.ToString();
                            string ivouchID = rsRecord.Fields["ID"].Value.ToString();
                            string cInvCode = rsRecord.Fields["cInvCode"].Value.ToString();
                            string cWhCode = rsRecord.Fields["cWhCode"].Value.ToString();
                            string impoids = rsRecord.Fields["impoids"].Value.ToString();
                            string iRowNo = x.ToString();
                            string cInvSN = ds.Tables[1].DefaultView[j]["XLCode"].ToString();
                            string cBatch = rsRecord.Fields["cBatch"].Value.ToString();
                            x++;
                            string sqlinxl = "insert into ST_SNDetail_PROIN(ivouchsID,ivouchID,cInvCode,cWhCode,impoids,csource,iSNPreState,iRowNo,cInvSN,cBatch) " +
                               "Values(" + ivouchsID + "," + ivouchID + ",'" + cInvCode + "','" + cWhCode + "'," + impoids + ",'生产订单',0," + iRowNo + ",'" + cInvSN + "','" + cBatch + "')";
                            objADO = null;
                            iOptions = 0;
                            oCon.Execute(sqlinxl, out objADO, iOptions);
                            //判断cInvSN>1
                            ADODB.Recordset rs = new ADODB.Recordset();
                            string strRsSQL = "SELECT * FROM ST_SNDetail_PROIN WHERE cInvSN='" + cInvSN + "'";
                            rs.Open(strRsSQL, oCon, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockOptimistic, (int)ADODB.CommandTypeEnum.adCmdText);
                            if (rs.RecordCount > 1)
                            {
                                //oCon.RollbackTrans();
                                damResult.message = "序列号:" + cInvSN + "重复";
                                jsonResult = JsonConvert.SerializeObject(damResult);
                                return jsonResult;
                            }
                        }
                    }
                    rsRecord.MoveNext();
                }
                string xlhList = "";
                for (int i = 0; i < ds.Tables[1].DefaultView.Count; i++)
                {
                    if (i > 0) xlhList += ",";
                    xlhList += "'" + ds.Tables[1].DefaultView[i]["XLCode"].ToString() + "'";
                }
                DataSet stds = new DataSet();
                //DataTableName dtnsn = new DataTableName();
                //dtnsn.strTableName=
                string insql = "select * from " + strYongYouDBName + ".dbo.ST_SNState with (nolock) where cInvSN in (" + xlhList + ")";
                stds = CustomizableDesignBLL.GetData(insql);
                for (int i = 0; i < ds.Tables[1].DefaultView.Count; i++)
                {
                    bool flags = false;
                    for (int j = 0; j < stds.Tables[0].DefaultView.Count; j++)
                    {
                        if (ds.Tables[1].DefaultView[i]["XLCode"].ToString() == stds.Tables[0].DefaultView[j]["cInvSN"].ToString())
                        {
                            flags = true;

                            break;
                        }
                    }
                    if (!flags)
                    {
                        insql = "insert into " + strYongYouDBName + ".dbo.ST_SNState(cInvCode,cInvSN,cBatch,cwhcode,iSNState)values('" + ds.Tables[1].DefaultView[i]["cInvCode"].ToString() + "','" + ds.Tables[1].DefaultView[i]["XLCode"].ToString() + "','" + ds.Tables[1].DefaultView[i]["cBatch"].ToString() + "','0401',1)";

                        objADO = null;
                        iOptions = 0;
                        oCon.Execute(insql, out objADO, iOptions);
                        string strPath = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Content/") + "log_in" + DateTime.Now.ToString("yyyyMMdd") + ".ini");
                        new YYAPI.Log().LogWrite(strPath, "日志入库" + DateTime.Now.ToString() + "：" + insql);

                    }
                    else
                    {
                        insql = "update " + strYongYouDBName + ".dbo.ST_SNState set cwhcode='0401',cBatch='" + ds.Tables[1].DefaultView[i]["cBatch"].ToString() + "',iSNState=1 where cInvSN='" + ds.Tables[1].DefaultView[i]["XLCode"].ToString() + "'";

                        objADO = null;
                        iOptions = 0;
                        oCon.Execute(insql, out objADO, iOptions);
                        string strPath = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Content/") + "log_in" + DateTime.Now.ToString("yyyyMMdd") + ".ini");
                        new YYAPI.Log().LogWrite(strPath, "日志入库" + DateTime.Now.ToString() + "：" + insql);

                    }
                }
                strMsg = new YYAPI.coapi().ToYYCCPRK_Audit(oCon, strID, strutfs1, strYongYouDBName, strZT, sYear, strUserCode, strUserPwd, sDate, sServer);
                if (!string.IsNullOrEmpty(strMsg))
                {
                    //oCon.RollbackTrans();
                    damResult.message = "调用审核API错误：" + strMsg;
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
                }

                string upsql = "update ST_SNState set iSNState=2,iSNOperateCount=2 where cInvSN in (" + xlhList + ")";
                objADO = null;
                iOptions = 0;
                oCon.Execute(upsql, out objADO, iOptions);
                //
                upsql = "update ST_SNDetail_PROIN set iSNPreState=13,iSNOperateCount=2,cSNDefine1=impoids where cInvSN in (" + xlhList + ")";
                objADO = null;
                iOptions = 0;
                oCon.Execute(upsql, out objADO, iOptions);
                //
                upsql = "update mom_SNDetail set iSNCurState=13,bused=1 where cInvSN in (" + xlhList + ")";
                objADO = null;
                iOptions = 0;
                oCon.Execute(upsql, out objADO, iOptions);
                //
                string sql = "update " + strZ8DataBase + ".dbo.T_dispatch_serialno set zzBG='已入库' where OrderSerialID in(" + xlhList + ")";
                objADO = null;
                iOptions = 0;
                oCon.Execute(sql, out objADO, iOptions);
                //
                sql = "update " + strZ8DataBase + ".dbo.T_GXbg set State=1 where SerialNum='" + strPKValue + "'";
                objADO = null;
                iOptions = 0;
                oCon.Execute(sql, out objADO, iOptions);
                //
                sql = "update " + strZ8DataBase + ".dbo.T_GXbgDetail set State=1 where XLCode in(" + xlhList + ")";
                objADO = null;
                iOptions = 0;
                oCon.Execute(sql, out objADO, iOptions);
                //
                //oCon.CommitTrans();
                //string upsql = "update " + strYongYouDBName + ".dbo.ST_SNState set iSNState=2 where cInvSN in (" + xlhList + ")";
                //string sql = "update T_dispatch_serialno set zzBG='已入库' where OrderSerialID in(" + xlhList + ")";
                //List<string> strlist = new List<string>();
                //strlist.Add(upsql);
                //strlist.Add(sql);
                //strlist.Add("update T_GXbg set State=1 where SerialNum='" + strPKValue + "'");
                //strlist.Add("update T_GXbgDetail set State=1 where XLCode in(" + xlhList + ")");
                //try
                //{
                //    CustomizableDesignBLL.ExecSQL(strlist);
                //}
                //catch (Exception ex)
                //{
                //    damResult.message = "回刷数据失败：" + ex.Message;
                //    jsonResult = JsonConvert.SerializeObject(damResult);
                //    return jsonResult;
                //}
            }
            catch (Exception ex)
            {
                //oCon.RollbackTrans();
                damResult.message = "保存出错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }


            damResult.success = true;
            damResult.message = "";
            jsonResult = JsonConvert.SerializeObject(damResult);
            return jsonResult;
        }

        #region 获取最大流水号
        public int GetMaxLs(string Info, string TableName, string ColumnName, int len)
        {
            DataSet ds = new DataSet();
            List<DataTableName> dtnList = new List<DataTableName>();
            DataTableName dtn = new DataTableName();
            dtn.strSelectSQL = "SELECT MAX(SubString(" + ColumnName + ",LEN(" + ColumnName + ")-" + (len - 1) + "," + len + ")) MaxCode FROM " + TableName + " WHERE " + ColumnName + " like '" + Info + "%'";
            dtn.strTableName = "LS";
            dtnList.Add(dtn);
            try
            {
                ds = CustomizableDesignBLL.GetData(dtnList, false);
            }
            catch (Exception ex)
            {
                return 1;
            }
            List<dynamic> varList = new List<dynamic>();
            if (ds.Tables[0].DefaultView.Count > 0 && !string.IsNullOrEmpty(ds.Tables[0].DefaultView[0][0].ToString()))
            {
                return int.Parse(ds.Tables[0].DefaultView[0][0].ToString()) + 1;

            }
            return 1;

        }
        #endregion
        //DJ 采购单号

        public string getFHInfo()
        {
            string jsonResult = string.Empty;
            //构造反馈对象
            dynamic damResult = new ExpandoObject();
            damResult.success = false;
            damResult.message = "获取失败";
            DataSet ds = new DataSet();
            string sql = "";
            sql = "select *,CONVERT(varchar(100), dDate, 23)ddatex from " + Common.GetdatabaseName("") + ".dbo.dispatchlist where dDate>'2020-05-31' and DLID in (select DLID FROM " + Common.GetdatabaseName("") + ".dbo.DispatchLists WHERE isnull(fOutQuantity,0)<>iQuantity) " +
            "order by ddate desc";
            try
            {
                ds = CustomizableDesignBLL.GetData(sql);
            }
            catch (Exception ex)
            {
                damResult.message = "查询失败" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            if (ds.Tables[0].DefaultView.Count == 0)
            {
                damResult.message = "暂无出库任务";
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            List<dynamic> varList = new List<dynamic>();
            foreach (DataRowView drv in ds.Tables[0].DefaultView)
            {
                var item = Trade.DBUtility.ExtendObject.AutoMap(drv.Row);
                varList.Add(item);
            }
            damResult.success = true;
            damResult.message = "正常";
            damResult.data = varList;
            jsonResult = JsonConvert.SerializeObject(damResult);
            return jsonResult;
        }
        public string getFHDetailList(string ID)
        {
            string jsonResult = string.Empty;
            //构造反馈对象
            dynamic damResult = new ExpandoObject();
            damResult.success = false;
            damResult.message = "获取失败";
            DataSet ds = new DataSet();
            string sql = "";
            sql = "select a.*,b.cInvName from " + Common.GetdatabaseName("") + ".dbo.dispatchlists a left join " + Common.GetdatabaseName("") + ".dbo.inventory b on a.cInvCode=b.cInvCode where DLID='" + ID + "'";
            try
            {
                ds = CustomizableDesignBLL.GetData(sql);
            }
            catch (Exception ex)
            {
                damResult.message = "查询失败" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            if (ds.Tables[0].DefaultView.Count == 0)
            {
                damResult.message = "暂无出库任务";
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            List<dynamic> varList = new List<dynamic>();
            foreach (DataRowView drv in ds.Tables[0].DefaultView)
            {
                var item = Trade.DBUtility.ExtendObject.AutoMap(drv.Row);
                varList.Add(item);
            }
            damResult.success = true;
            damResult.data = varList;
            jsonResult = JsonConvert.SerializeObject(damResult);
            return jsonResult;
        }
        public string CKSave(string MasterData, string DetailData, string UserID, string Pwd)
        {
            string jsonResult = string.Empty;
            //构造反馈对象
            dynamic damResult = new ExpandoObject();
            damResult.success = false;
            damResult.message = "获取失败";
            string strPKValue = "";
            //测试直接JSON转换数据集的 这个是可以做的，但是不是需要现在做的。因为这个是整个框架都要改了。没那个时间
            //DataSet dstest = JsonConvert.DeserializeObject<DataSet>(strDsData);
            string strTableName = "T_CPCK";
            string strTableDetail = strTableName + "Product";
            //先获取数据库数据，如果没有数据就新增
            List<DataTableName> dtnGetDataList = new List<DataTableName>();
            DataSet dsGetData = new DataSet();
            DataTableName dtnGetData = new DataTableName();
            dtnGetData.strSelectSQL = "Select * from " + strTableName + " where 1=0";
            dtnGetData.strTableName = strTableName;
            dtnGetDataList.Add(dtnGetData);
            //
            dtnGetData = new DataTableName();
            dtnGetData.strSelectSQL = "Select * from " + strTableDetail + " where 1=0 ";
            dtnGetData.strTableName = strTableDetail;
            dtnGetDataList.Add(dtnGetData);
            //
            try
            {
                dsGetData = CustomizableDesignBLL.GetData(dtnGetDataList, true);
            }
            catch (Exception ex)
            {
                damResult.message = "获取模块数据表结构失败:" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            if (dsGetData.Tables[strTableName].DefaultView.Count == 0)
            {
                dsGetData.Tables[strTableName].Rows.Add(dsGetData.Tables[0].NewRow());
            }
            //
            #region 主表部分
            JavaScriptSerializer Serializer = new JavaScriptSerializer();
            List<DataSave> ListDsData = Serializer.Deserialize<List<DataSave>>(MasterData);
            for (int i = 0; i < ListDsData.Count; i++)
            {
                DataSave dtmtsave = ListDsData[i];
                if (dsGetData.Tables[dtmtsave.TableName].Columns.Contains(dtmtsave.CoulumName))
                {


                    if (dsGetData.Tables[dtmtsave.TableName].Columns[dtmtsave.CoulumName].DataType.Name == "Boolean")
                    {
                        string strValue = dtmtsave.CoulunValue;


                        bool bisValue = false;
                        if (Boolean.TryParse(strValue, out bisValue))
                            dsGetData.Tables[dtmtsave.TableName].DefaultView[0][dtmtsave.CoulumName] = bisValue;
                        else
                        {
                            if (strValue.ToString().ToLower() == "true" || strValue.ToString().ToLower() == "1")
                                dsGetData.Tables[dtmtsave.TableName].DefaultView[0][dtmtsave.CoulumName] = true;
                            else
                                dsGetData.Tables[dtmtsave.TableName].DefaultView[0][dtmtsave.CoulumName] = false;
                        }
                    }
                    else
                    {
                        if (!dsGetData.Tables[dtmtsave.TableName].Columns[dtmtsave.CoulumName].ReadOnly)
                            dsGetData.Tables[dtmtsave.TableName].DefaultView[0][dtmtsave.CoulumName] = dtmtsave.CoulunValue;
                        //
                    }
                }
            }
            //一些必输项自动赋值
            strPKValue = DateTime.Now.ToString("yyyyMMdd") + GetMaxLs(DateTime.Now.ToString("yyyyMMdd"), strTableName, "SerialNum", 4).ToString("0000");
            if (dsGetData.Tables[strTableName].Columns.Contains("SaveTime"))
                dsGetData.Tables[strTableName].DefaultView[0]["SaveTime"] = DateTime.Now.ToString();
            dsGetData.Tables[strTableName].DefaultView[0]["SerialNum"] = strPKValue;
            dsGetData.Tables[strTableName].DefaultView[0].EndEdit();
            #endregion
            #region 细表部分
            // 先删除细表数据
            while (dsGetData.Tables[strTableDetail].DefaultView.Count > 0)
                dsGetData.Tables[strTableDetail].DefaultView[0].Delete();
            JavaScriptSerializer SerializerDetail = new JavaScriptSerializer();
            dynamic ListDsDataDetail = Serializer.Deserialize<dynamic>(DetailData);
            for (int i = 0; i < ListDsDataDetail.Length; i++)
            {
                DataRow drDetailNew = dsGetData.Tables[strTableDetail].NewRow();
                dynamic dtmtsavelist = ListDsDataDetail[i];
                foreach (dynamic dsv in dtmtsavelist)
                {
                    String strDetaliTablename = string.Empty;
                    String strDetaliCoulumName = string.Empty;
                    String strDetaliCoulunValue = string.Empty;
                    foreach (string strkey in dsv.Keys)
                    {
                        if (strkey == "TableName")
                            strDetaliTablename = dsv[strkey].ToString();
                        if (strkey == "CoulumName")
                            strDetaliCoulumName = dsv[strkey].ToString();
                        if (strkey == "CoulunValue")
                            strDetaliCoulunValue = dsv[strkey].ToString();
                    }
                    //
                    if (!dsGetData.Tables[strDetaliTablename].Columns.Contains(strDetaliCoulumName))
                        continue;
                    //
                    if (!dsGetData.Tables[strDetaliTablename].Columns[strDetaliCoulumName].ReadOnly && strDetaliCoulumName != "SortID" && strDetaliCoulumName != "ISDel")
                    {
                        if (dsGetData.Tables[strDetaliTablename].Columns.Contains(strDetaliCoulumName))
                        {
                            if (strDetaliCoulunValue == null || strDetaliCoulunValue == string.Empty)
                                continue;
                            if (dsGetData.Tables[strDetaliTablename].Columns[strDetaliCoulumName].DataType.Name == "Int32")
                            {
                                decimal dec = Convert.ToDecimal(strDetaliCoulunValue);
                                drDetailNew[strDetaliCoulumName] = Convert.ToInt32(dec);
                            }
                            else
                            {
                                drDetailNew[strDetaliCoulumName] = strDetaliCoulunValue;
                            }
                        }
                    }
                }
                //赋值一些必要的值
                drDetailNew["SerialNum"] = strPKValue;
                dsGetData.Tables[strTableDetail].Rows.Add(drDetailNew);
            }
            #endregion
            try
            {
                CustomizableDesignBLL.SaveData(dsGetData, dtnGetDataList);
            }
            catch (Exception ex)
            {
                damResult.message = "保存模块数据报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            #region 重新获取数据
            DataSet ds = new DataSet();
            List<DataTableName> dtnList = new List<DataTableName>();
            DataTableName dtn = new DataTableName();
            dtn.strSelectSQL = "Select * from " + strTableName + " where SerialNum= '" + strPKValue + "'";
            dtn.strTableName = strTableName;
            dtnList.Add(dtn);
            dtn = new DataTableName();
            dtn.strSelectSQL = "Select * from " + strTableDetail + " where SerialNum= '" + strPKValue + "' ";
            dtn.strTableName = strTableDetail;
            dtnList.Add(dtn);
            try
            {
                ds = CustomizableDesignBLL.GetData(dtnList, false);
            }
            catch (Exception ex)
            {
                damResult.message = "获取保存后数据报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            #endregion
            string xlhList = "";
            for (int i = 0; i < ds.Tables[1].DefaultView.Count; i++)
            {
                if (i > 0) xlhList += ",";
                xlhList += "'" + ds.Tables[1].DefaultView[i]["XLCode"].ToString() + "'";
            }

            string strConn = ConfigurationManager.ConnectionStrings["ConStr1"].ConnectionString;
            ADODB.Connection oCon = new ADODB.Connection();
            string strZ8DataBase = ConfigurationManager.AppSettings["Z8DataBase"];
            if (strZ8DataBase == null || strZ8DataBase == "")
            {
                damResult.message = "Z8DataBase没有设置";
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            string strYongYouDBName = Common.GetdatabaseName("");
            string strZT = strYongYouDBName.Substring(7, 3);
            string sAccID = strZT;
            string sYear = DateTime.Now.Year.ToString();
            string strUserCode = UserID;
            string strUserPwd = Pwd;
            string sDate = DateTime.Now.ToString("yyyy-MM-dd");
            string sServer = Common.getU8SerVerIP();// "172.16.1.20";// strServerIP; 
            //if (Common.getBisTest())
            //{
            //    sDate = new DateTime(2019, 2, 28).ToString("yyyy-MM-dd");
            //}
            //
            //if (string.IsNullOrEmpty(strUserCode))
            //{
                strUserCode = "sxc";
                strUserPwd = "637813";

                //damResult.message = "strUserCode没有设置";
                //jsonResult = JsonConvert.SerializeObject(damResult);
                //return jsonResult;
            //}
            string FHID = ds.Tables[0].DefaultView[0]["FHID"].ToString();
            List<DataTableName> list = new List<DataTableName>();
            dtn = new DataTableName();
            dtn.strSelectSQL = "select * from " + strYongYouDBName + ".dbo.dispatchlist where DLID='" + FHID + "'";
            dtn.strTableName = "dispatchlist";
            list.Add(dtn);
            dtn = new DataTableName();
            dtn.strSelectSQL = "select * from " + strYongYouDBName + ".dbo.dispatchlists where DLID='" + FHID + "'";
            dtn.strTableName = "dispatchlists";
            list.Add(dtn);
            DataSet dsToU8 = new DataSet();
            try
            {
                oCon.CursorLocation = ADODB.CursorLocationEnum.adUseClient;
                oCon.ConnectionString = strConn;
                oCon.Open(strConn, "", "", -1);
                //开始事务，很关键
                //oCon.BeginTrans();
                dsToU8 = CustomizableDesignBLL.GetData(list, false);
                //因为要排序，所以传了ds.Copy()
                string strMsg = new YYAPI.coapi().ToYYXSCK(oCon, ds.Copy(), dsToU8, strYongYouDBName, strZT, sYear, strUserCode, strUserPwd, sDate, sServer, strPKValue);
                if (!string.IsNullOrEmpty(strMsg))
                {
                    oCon.RollbackTrans();
                    damResult.message = "调用销售出库API错误：" + strMsg;
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
                }
                ////
                //DataSet dsFromU8 = null;
                //List<DataTableName> dtnlist = new List<DataTableName>();
                //dtn = new DataTableName();
                //dtn.strSelectSQL = "select *,convert(nchar,convert(money,ufts),2) as ufts1 from " + strYongYouDBName + ".dbo.rdrecord32 where cdefine10='" + strPKValue + "'";
                //dtn.strTableName = "rdrecord32";
                //dtnlist.Add(dtn);
                //dtn = new DataTableName();
                //dtn.strSelectSQL = "select * from " + strYongYouDBName + ".dbo.rdrecords32 where cdefine27='" + strPKValue + "'";
                //dtn.strTableName = "rdrecords32";
                //dtnlist.Add(dtn);
                //try
                //{
                //    dsFromU8 = CustomizableDesignBLL.GetData(dtnlist, false);
                //}
                //catch (Exception ex)
                //{
                //    oCon.RollbackTrans();
                //    damResult.message = ("取U8产成品入库单出错：" + ex.Message);
                //    jsonResult = JsonConvert.SerializeObject(damResult);
                //    return jsonResult;
                //}
                ADODB.Recordset rsRecord = new ADODB.Recordset();
                string strRsSQLRecord = "select (select top 1 cWhCode from rdrecord32 where id=rdrecords32.id) cWhCode,(select top 1 convert(nchar,convert(money,ufts),2) from rdrecord32 where id=rdrecords32.id) utfs1,* from rdrecords32 where cdefine27='" + strPKValue + "'";
                rsRecord.Open(strRsSQLRecord, oCon, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockOptimistic, (int)ADODB.CommandTypeEnum.adCmdText);
                object objADO = null;
                int iOptions = 0;
                if (rsRecord.RecordCount == 0)
                {
                    //oCon.RollbackTrans();
                    damResult.message = "出库记录为空！";
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
                }
                string strID = rsRecord.Fields["id"].Value.ToString();
                string strutfs1 = rsRecord.Fields["utfs1"].Value.ToString();
                for (int i = 0; i < rsRecord.RecordCount; i++)
                {
                    int x = 1;
                    for (int j = 0; j < ds.Tables[1].DefaultView.Count; j++)
                    {
                        if (rsRecord.Fields["idlsid"].Value.ToString() == ds.Tables[1].DefaultView[j]["FHDID"].ToString())
                        {
                            //找到序列号的自定义项 
                            string cInvSN = ds.Tables[1].DefaultView[j]["XLCode"].ToString();
                            DataSet xlhds = new DataSet();
                            string xlhsql = "select * from " + strYongYouDBName + ".dbo.ST_SNState with (nolock) where cInvSN ='" + cInvSN + "'";
                            xlhds = CustomizableDesignBLL.GetData(xlhsql);


                            string ivouchsID = rsRecord.Fields["AutoID"].Value.ToString();
                            string ivouchID = rsRecord.Fields["ID"].Value.ToString();
                            string cInvCode = rsRecord.Fields["cInvCode"].Value.ToString();
                            string cWhCode = rsRecord.Fields["cWhCode"].Value.ToString();
                            string idlsid = rsRecord.Fields["idlsid"].Value.ToString();
                            string iRowNo = x.ToString();
                           
                            string cBatch = rsRecord.Fields["cBatch"].Value.ToString();
                            x++;
                            string sqlinxl = "insert into ST_SNDetail_SaleOut(ivouchsID,ivouchID,cInvCode,cWhCode,idlsid,csource,iSNPreState,iRowNo,cInvSN,cBatch,cprewhcode,cpreBatch,csndefine1,csndefine2) " +
                                 "Values(" + ivouchsID + "," + ivouchID + ",'" + cInvCode + "','" + cWhCode + "'," + idlsid + ",'发货单',2," + iRowNo + ",'" + cInvSN + "','" + cBatch + "','" + cWhCode + "','" + cBatch + "','" + xlhds.Tables[0].DefaultView[0]["csndefine1"] + "','" + xlhds.Tables[0].DefaultView[0]["csndefine2"] + "')";
                            objADO = null;
                            iOptions = 0;
                            oCon.Execute(sqlinxl, out objADO, iOptions);
                            //判断cInvSN>1
                            ADODB.Recordset rs = new ADODB.Recordset();
                            string strRsSQL = "SELECT * FROM ST_SNDetail_SaleOut with (nolock) WHERE cInvSN='" + cInvSN + "'";
                            rs.Open(strRsSQL, oCon, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockOptimistic, (int)ADODB.CommandTypeEnum.adCmdText);
                            if (rs.RecordCount > 1)
                            {
                                //oCon.RollbackTrans();
                                damResult.message = "序列号:" + cInvSN + "重复";
                                jsonResult = JsonConvert.SerializeObject(damResult);
                                return jsonResult;
                            }
                        }
                    }
                    rsRecord.MoveNext();
                }
                DataSet stds = new DataSet();
                string insql = "select * from " + strYongYouDBName + ".dbo.ST_SNState with (nolock) where cInvSN in (" + xlhList + ")";
                stds = CustomizableDesignBLL.GetData(insql);

                for (int i = 0; i < ds.Tables[1].DefaultView.Count; i++)
                {
                    bool flags = false;
                    for (int j = 0; j < stds.Tables[0].DefaultView.Count; j++)
                    {
                        if (ds.Tables[1].DefaultView[i]["XLCode"].ToString() == stds.Tables[0].DefaultView[j]["cInvSN"].ToString())
                        {
                            flags = true;
                            break;
                        }
                    }
                    if (!flags)
                    {
                        //不可能不存在
                        insql = "insert into " + strYongYouDBName + ".dbo.ST_SNState(cInvCode,cInvSN,cBatch,cwhcode,iSNState)values('" + ds.Tables[1].DefaultView[i]["cInvCode"].ToString() + "','" + ds.Tables[1].DefaultView[i]["XLCode"].ToString() + "','" + ds.Tables[1].DefaultView[i]["cBatch"].ToString() + "','" + ds.Tables[0].DefaultView[0]["cWhCode"].ToString() + "',3)";
                        objADO = null;
                        iOptions = 0;
                        oCon.Execute(insql, out objADO, iOptions);
                        //oCon.CommitTrans();
                        string strPath = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Content/") + "log_Out" + DateTime.Now.ToString("yyyyMMdd") + ".ini");
                        new YYAPI.Log().LogWrite(strPath, "日志出库" + DateTime.Now.ToString() + "：" + insql);
                    }
                    else
                    {
                        insql = "update " + strYongYouDBName + ".dbo.ST_SNState set cwhcode='" + ds.Tables[0].DefaultView[0]["cWhCode"].ToString() + "',cBatch='" + ds.Tables[1].DefaultView[i]["cBatch"].ToString() + "',iSNState=3 where cInvSN='" + ds.Tables[1].DefaultView[i]["XLCode"].ToString() + "'";
                        objADO = null;
                        iOptions = 0;
                        oCon.Execute(insql, out objADO, iOptions);
                        //oCon.CommitTrans();
                        string strPath = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Content/") + "log_out" + DateTime.Now.ToString("yyyyMMdd") + ".ini");
                        new YYAPI.Log().LogWrite(strPath, "日志出库" + DateTime.Now.ToString() + "：" + insql);
                    }
                }

                //oCon.CommitTrans();

                //oCon.BeginTrans();
                //try
                //{
                    strMsg = new YYAPI.coapi().ToYYXSCK_Audit(oCon, strID, strutfs1, strYongYouDBName, strZT, sYear, strUserCode, strUserPwd, sDate, sServer);
                    if (!string.IsNullOrEmpty(strMsg))
                    {
                        //oCon.RollbackTrans();
                        damResult.message = "调用审核API错误：" + strMsg;
                        jsonResult = JsonConvert.SerializeObject(damResult);
                        return jsonResult;
                    }

                    string upsql = "update " + strYongYouDBName + ".dbo.ST_SNState set iSNState=9,iSNOperateCount=3 where cInvSN in (" + xlhList + ")";
                    objADO = null;
                    iOptions = 0;
                    oCon.Execute(upsql, out objADO, iOptions);
                    //
                    string sql = "update " + strZ8DataBase + ".dbo.T_dispatch_serialno set zzBG='已出库' where OrderSerialID in(" + xlhList + ")";
                    objADO = null;
                    iOptions = 0;
                    oCon.Execute(sql, out objADO, iOptions);

                    string sql1 = "update " + strZ8DataBase + ".dbo.t_jhuo set state='1' where serialnum in(select serialnum from " + strZ8DataBase + ".dbo.t_jhuo_b where  xlcode in(" + xlhList + "))";
                    objADO = null;
                    iOptions = 0;
                    oCon.Execute(sql, out objADO, iOptions);
                    string sql2 = "update " + strZ8DataBase + ".dbo.t_jhuo_b set state='1' where xlcode in(" + xlhList + ")";
                    objADO = null;
                    iOptions = 0;
                    oCon.Execute(sql, out objADO, iOptions);

                    //oCon.CommitTrans();
                //}
                //catch (Exception ex)
                //{
                //    //oCon.RollbackTrans();
                //    throw ex; 
                //} 
            }
            catch (Exception ex)
            {
                //oCon.RollbackTrans();
                damResult.message = "错误：" + ex.Message;
                UFIDA.U8.PUB.LogHelper.WriteLine(damResult.message);
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            damResult.success = true;
            damResult.message = "";
            jsonResult = JsonConvert.SerializeObject(damResult);
            return jsonResult;
        }
        //DJ 采购订单的序列号扫描

        public string GetCGInfo(string XLCode)
        {
            string jsonResult = string.Empty;
            //构造反馈对象
            dynamic damResult = new ExpandoObject();
            damResult.success = false;
            damResult.message = "获取失败";
            DataSet dsDetail = new DataSet();
            DataSet ds = new DataSet();
            string comcode = Common.GetdatabaseName("");
            string SQL = "select o.* from " + comcode + ".dbo.ST_SNState s with (nolock) inner join " + comcode + ".dbo.po_podetails m with (nolock) on s.cSNDefine2=m.ID inner join " + comcode + ".dbo.po_pomain o with (nolock) on m.POID=o.POID where s.cInvSN='" + XLCode + "'";
            try
            {
                dsDetail = CustomizableDesignBLL.GetData(SQL);
            }
            catch (Exception ex)
            {
                damResult.message = "获取信息报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            if (dsDetail.Tables[0].DefaultView.Count == 0)
            {
                damResult.message = "未找到该序列号!";
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            SQL = "select * from " + comcode + ".dbo.ST_SNDetail_PUIN where cInvSN='" + XLCode + "'";
            DataSet ddss = new DataSet();
            try
            {
                ddss = CustomizableDesignBLL.GetData(SQL);
            }
            catch (Exception ex)
            {
                damResult.message = "获取信息报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            if (ddss.Tables[0].DefaultView.Count > 0)
            {
                damResult.message = "此序列号已入库";
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;

            }
            string SerialNum = dsDetail.Tables[0].DefaultView[0]["cpoid"].ToString();
            List<DataTableName> dtnlist = new List<DataTableName>();
            DataTableName dtn = new DataTableName();
            dtn.strSelectSQL = "select * from v_cginstorage where cInvSN='" + XLCode + "'";
            dtn.strTableName = "v_cginstorage";
            dtnlist.Add(dtn);
            try
            {
                ds = CustomizableDesignBLL.GetData(dtnlist, false);
            }
            catch (Exception ex)
            {
                damResult.message = "数据获取失败" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            List<dynamic> varList = new List<dynamic>();
            //List<dynamic> varListDetail = new List<dynamic>();
            if (ds.Tables[0].DefaultView.Count > 0)
            {
                foreach (DataRowView drv in ds.Tables[0].DefaultView)
                {
                    var item = Trade.DBUtility.ExtendObject.AutoMap(drv.Row);
                    varList.Add(item);
                }
                //foreach (DataRowView drv in ds.Tables[1].DefaultView)
                //{
                //    var item = Trade.DBUtility.ExtendObject.AutoMap(drv.Row);
                //    varListDetail.Add(item);
                //}
                damResult.success = true;
                damResult.message = SerialNum;
                damResult.data = varList;
                //damResult.Fdata = varListDetail;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            jsonResult = "{\"success\":false   ,\"message\":\"查询条码发生错误！\"}";
            return jsonResult;
        }
        //DJ 保存
        public string SaveCGIn(string strPKValue, string UserID, string Pwd, string swList, string cWhCode)
        {
            string jsonResult = string.Empty;
            //构造反馈对象
            dynamic damResult = new ExpandoObject();
            damResult.success = false;
            damResult.message = "获取失败";

            if (string.IsNullOrEmpty(swList))
            {
                damResult.message = "扫描的序列号列表不能为空!";
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            cWhCode = "0401";
            string strYongYouDBName = Common.GetdatabaseName("");

            string strZT = strYongYouDBName.Substring(7, 3);
            string sAccID = strZT;
            string sYear = DateTime.Now.Year.ToString();

            string strUserCode = UserID;
            string strUserPwd = Pwd;
            string sDate =  DateTime.Now.ToString("yyyy-MM-dd");
            string sServer = Common.getU8SerVerIP();// "172.16.1.20";// strServerIP; 
            //if (string.IsNullOrEmpty(strUserCode))
            //{
                strUserCode = "sxc";
                strUserPwd = "637813";

                //damResult.message = "strUserCode没有设置";
                //jsonResult = JsonConvert.SerializeObject(damResult);
                //return jsonResult;
            //}
            string strPKValues = "";
            #region 重新获取数据
            DataSet ds = new DataSet();
            List<DataTableName> dtnList = new List<DataTableName>();
            //采购订单信息
            DataTableName dtn = new DataTableName();
            dtn.strSelectSQL = "Select  a.cvencode,a.cpoid,b.cinvcode,b.iTaxPrice,b.iQuantity,b.id ,b.sotype,b.sodid,b.csocode from " + strYongYouDBName + ".dbo.po_pomain a inner join " + strYongYouDBName + ".dbo.po_podetails b  on a.poid=b.poid where a.cpoid in(" + strPKValue + ")";
            dtn.strTableName = "po_podetails";
            dtnList.Add(dtn);
            //扫描的订单的信息  不一定相同 可能拆分多个订单
            dtn = new DataTableName();
            dtn.strSelectSQL = "select cpoid,cinvcode,count(*)iQuantity,id,Define33,'' as iTaxPrice  from v_cginstorage where cinvSN in(" + swList + ") and cpoid in(" + strPKValue + ") group by cpoid, cinvcode,id,Define33";
            dtn.strTableName = "v_cginstorage";
            dtnList.Add(dtn);
            //序列号的信息
            dtn = new DataTableName();
            dtn.strSelectSQL = "select *  from v_cginstorage where cinvSN in(" + swList + ") and cpoid in(" + strPKValue + ")";
            dtn.strTableName = "v_xlh";
            dtnList.Add(dtn);
            //表头信息
            dtn = new DataTableName();
            dtn.strSelectSQL = "select * from " + strYongYouDBName + ".dbo. po_pomain where cpoid in(" + strPKValue + ")";
            dtn.strTableName = "po_pomain";
            dtnList.Add(dtn);
            try
            {
                ds = CustomizableDesignBLL.GetData(dtnList, false);
            }
            catch (Exception ex)
            {
                damResult.message = "获取保存后数据报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            #endregion

            string strConn = ConfigurationManager.ConnectionStrings["ConStr1"].ConnectionString;
            ADODB.Connection oCon = new ADODB.Connection();
            string strZ8DataBase = ConfigurationManager.AppSettings["Z8DataBase"];
            if (strZ8DataBase == null || strZ8DataBase == "")
            {
                damResult.message = "Z8DataBase没有设置";
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            //合并中间表
            #region 合并相同存货的数量
            //ds.Tables[1].DefaultView.Sort = "MoDID";
            //DataSet dsff = ds.Clone();
            //int len = ds.Tables[1].DefaultView.Count;
            //decimal qty = 0;
            //string Modid = "";
            //bool flag = false;
            //for (int i = 0; i < len; )
            //{
            //    flag = true;
            //    bool xx = false;//是否进入以下循环
            //    qty = decimal.Parse(ds.Tables[1].DefaultView[i]["qty"].ToString()); ;
            //    Modid = ds.Tables[1].DefaultView[i]["Modid"].ToString();
            //    for (int j = i + 1; j < len; j++)
            //    {
            //        xx = true;
            //        if (Modid == ds.Tables[1].DefaultView[j]["Modid"].ToString())
            //        {
            //            qty += 1;
            //            ds.Tables[1].DefaultView[j]["qty"] = qty;
            //            i = j;
            //        }
            //        else
            //        {
            //            flag = false;
            //            ds.Tables[1].DefaultView[i]["qty"] = qty;
            //            ds.Tables[1].DefaultView[i].EndEdit();
            //            dsff.Tables[1].Rows.Add(ds.Tables[1].DefaultView[i].Row.ItemArray);
            //            i = j;
            //            break;
            //        }

            //    }
            //    if (!xx) i++;
            //}
            //if (flag)
            //{
            //    ds.Tables[1].DefaultView[len - 1]["qty"] = qty;
            //    ds.Tables[1].DefaultView[len - 1].EndEdit();
            //    dsff.Tables[1].Rows.Add(ds.Tables[1].DefaultView[len - 1].Row.ItemArray);
            //}
            //dsff.Tables[0].Rows.Add(ds.Tables[0].DefaultView[0].Row.ItemArray);
            //for (int w = 0; w < dsff.Tables[1].DefaultView.Count; w++)
            //{
            //    if (strPKValues != "") strPKValues += ",";
            //    strPKValues += "'" + dsff.Tables[1].DefaultView[w]["SerialID"].ToString() + "'";
            //}
            #endregion
            //对照扫描数据 给对应物料加个数量和单价
            for (int i = 0; i < ds.Tables["v_cginstorage"].DefaultView.Count; i++)
            {
                string cinvcode = ds.Tables["v_cginstorage"].DefaultView[i]["cinvcode"].ToString();
                string iQuantity = ds.Tables["v_cginstorage"].DefaultView[i]["iQuantity"].ToString();
                string id = ds.Tables["v_cginstorage"].DefaultView[i]["id"].ToString();
                for (int k = 0; k < ds.Tables["po_podetails"].DefaultView.Count; k++)
                {
                    string cinvcode1 = ds.Tables["po_podetails"].DefaultView[k]["cinvcode"].ToString();
                    string iTaxPrice1 = ds.Tables["po_podetails"].DefaultView[k]["iTaxPrice"].ToString();
                    string iQuantity1 = ds.Tables["po_podetails"].DefaultView[k]["iQuantity"].ToString();
                    string id1 = ds.Tables["po_podetails"].DefaultView[k]["id"].ToString();
                    if (id.Trim() == id1.Trim())
                    {
                        if (decimal.Parse(iQuantity) > decimal.Parse(iQuantity1))
                        {
                            damResult.message = "扫描的序列号合计数大于采购订单数,检查是否重复扫描!";//理论上不会发生  除非重复扫描
                            jsonResult = JsonConvert.SerializeObject(damResult);
                            return jsonResult;
                        }
                        ds.Tables["v_cginstorage"].DefaultView[i]["iTaxPrice"] = iTaxPrice1;
                        ds.Tables["v_cginstorage"].DefaultView[i].EndEdit();
                        continue;
                    }

                }
            }
            string tmList = swList.Replace("'", "");
            string tm = tmList.Split(',')[0];
            //检验是否已生成入库单
            //DJ  因为可能重复扫同一个采购订单的记录  所以没法判断是否已经生成入库单 只能通过序列号入库的表判断 在扫码的时候已经判断过  问题是重复点提交该怎么处理？  先采取用第一条扫描记录条码号来判断
            string sqlcin = "select * from " + strYongYouDBName + ".dbo.rdrecord01 where cdefine10='" + tm + "'";
            try
            {
                DataSet sqlds = CustomizableDesignBLL.GetData(sqlcin);
                if (sqlds.Tables[0].DefaultView.Count > 0)
                {
                    damResult.message = "已经生成此单据的采购入库单,请前往U8处理,单号为" + sqlds.Tables[0].DefaultView[0]["cCode"].ToString();
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
                }
            }
            catch (Exception ex)
            {
                damResult.message = "sql有误" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            try
            {
                oCon.CursorLocation = ADODB.CursorLocationEnum.adUseClient;
                oCon.ConnectionString = strConn;
                oCon.Open(strConn, "", "", -1);
                //开始事务，很关键
                //oCon.BeginTrans();
                //因为要排序，所以传了ds.Copy()
                string strMsg = new YYAPI.coapi().ToYYCGRK(oCon, ds, strYongYouDBName, strZT, sYear, strUserCode, strUserPwd, sDate, sServer, strPKValue, tm);
                if (!string.IsNullOrEmpty(strMsg))
                {
                    //oCon.RollbackTrans();
                    damResult.message = "调用采购入库API错误：" + strMsg;
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
                }

                //ADODB.Recordset rsRecord = new ADODB.Recordset();
                string strRsSQLRecord = "select (select top 1 cWhCode from " + strYongYouDBName + ".dbo.rdrecord01 where id=rdrecords01.id) cWhCode,(select top 1 cinvname from " + strYongYouDBName + ".dbo.Inventory where cinvcode=rdrecords01.cinvcode) cinvname,(select top 1 convert(nchar,convert(money,ufts),2) from " + strYongYouDBName + ".dbo.rdrecord01 where id=rdrecords01.id) utfs1,* from " + strYongYouDBName + ".dbo.rdrecords01 where cdefine25 ='" + tm + "'";
                DataSet resDs = CustomizableDesignBLL.GetData(strRsSQLRecord);
                //rsRecord.Open(strRsSQLRecord, oCon, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockOptimistic, (int)ADODB.CommandTypeEnum.adCmdText);
                //object objADO = null;
                //int iOptions = 0;
                if (resDs.Tables[0].DefaultView.Count == 0)
                {
                    //oCon.RollbackTrans();
                    damResult.message = "入库记录为空！";
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
                }
                string strID = resDs.Tables[0].DefaultView[0]["id"].ToString();
                //成功传U8的单据 记录下扫描记录 防止出错
                List<DataTableName> ls = new List<DataTableName>();
                DataTableName dt = new DataTableName();
                string tmstr = swList.Replace("'", "");
                string[] tmls = tmstr.Split(',');
                for (int k = 0; k < tmls.Length; k++)
                {
                    dt = new DataTableName();
                    dt.strExecSQL = "insert into t_cgrklog values( '" + DateTime.Now.ToString() + "','" + strID + "','" + tmls[k] + "','插入')";
                    ls.Add(dt);
                }
                CustomizableDesignBLL.ExecSQL(ls);

                string strutfs1 = resDs.Tables[0].DefaultView[0]["utfs1"].ToString(); ;//rsRecord.Fields["utfs1"].Value.ToString();
                for (int i = 0; i < resDs.Tables[0].DefaultView.Count; i++)
                {
                    int x = 1;
                    for (int j = 0; j < ds.Tables["v_xlh"].DefaultView.Count; j++)
                    {
                        if (resDs.Tables[0].DefaultView[i]["iposid"].ToString() == ds.Tables["v_xlh"].DefaultView[j]["id"].ToString())
                        {
                            string ivouchsID = resDs.Tables[0].DefaultView[i]["AutoID"].ToString();//rsRecord.Fields["AutoID"].Value.ToString();
                            string ivouchID = resDs.Tables[0].DefaultView[i]["ID"].ToString();//rsRecord.Fields["ID"].Value.ToString();
                            string cInvCode = resDs.Tables[0].DefaultView[i]["cInvCode"].ToString(); //rsRecord.Fields["cInvCode"].Value.ToString();
                            string cinvname = resDs.Tables[0].DefaultView[i]["cinvname"].ToString(); //rsRecord.Fields["cinvname"].Value.ToString();
                            cWhCode = resDs.Tables[0].DefaultView[i]["cWhCode"].ToString();//rsRecord.Fields["cWhCode"].Value.ToString();
                            string impoids = resDs.Tables[0].DefaultView[i]["iposid"].ToString();//rsRecord.Fields["iposid"].Value.ToString();
                            string iRowNo = x.ToString();
                            string cInvSN = ds.Tables["v_xlh"].DefaultView[j]["cInvSN"].ToString();
                            string cBatch = resDs.Tables[0].DefaultView[i]["cBatch"].ToString(); //rsRecord.Fields["cBatch"].Value.ToString();
                            x++;
                            string sqlinxl = "insert into " + strYongYouDBName + ".dbo.ST_SNDetail_PUIN(ivouchsID,ivouchID,cInvCode,cWhCode ,iSNPreState,iRowNo,cInvSN,cBatch,cSNDefine2) " +
                               "Values(" + ivouchsID + "," + ivouchID + ",'" + cInvCode + "','" + cWhCode + "',0," + iRowNo + ",'" + cInvSN + "','" + cBatch + "','" + impoids + "')";
                            //objADO = null;
                            //iOptions = 0;
                            //oCon.Execute(sqlinxl, out objADO, iOptions);
                            //判断cInvSN>1
                            CustomizableDesignBLL.ExecSQL(sqlinxl);
                            //ADODB.Recordset rs = new ADODB.Recordset();
                            string strRsSQL = "SELECT * FROM " + strYongYouDBName + ".dbo.ST_SNDetail_PUIN WHERE cInvSN='" + cInvSN + "'";
                            //CustomizableDesignBLL.ExecSQL(sqlinxl);
                            //rs.Open(strRsSQL, oCon, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockOptimistic, (int)ADODB.CommandTypeEnum.adCmdText);
                            //if (rs.RecordCount > 1)
                            //{
                            //    oCon.RollbackTrans();

                            //    dt = new DataTableName();
                            //    dt.strExecSQL = "insert into t_cgrklog values( '" + DateTime.Now.ToString() + "','" + strID + "','" + cInvSN + "','序列号重复')";
                            //    CustomizableDesignBLL.ExecSQL(dt);

                            //    damResult.message = "序列号:" + cInvSN + "重复";
                            //    jsonResult = JsonConvert.SerializeObject(damResult);
                            //    return jsonResult;
                            //}
                            //插入 t_dispatch_serialno                          
                            //判断cInvSN>1

                            string strNoSQL = "SELECT * FROM t_dispatch_serialno WHERE orderserialId='" + cInvSN + "'";
                            DataSet noDs = CustomizableDesignBLL.GetData(strNoSQL);
                            if (noDs.Tables[0].DefaultView.Count > 0)
                            {
                                strNoSQL = "delete from t_dispatch_serialno WHERE orderserialId='" + cInvSN + "'";
                                CustomizableDesignBLL.ExecSQL(strNoSQL);
                            }
                            strNoSQL = "insert into t_dispatch_serialno(isdel,invcode,cinvname,qty,orderserialId,zzbg ,cbatchno) " +
                              "Values('0','" + cInvCode + "','" + cinvname + "','1','" + cInvSN + "','','" + cBatch + "')";
                            CustomizableDesignBLL.ExecSQL(strNoSQL);
                        }
                    }
                    //rsRecord.MoveNext();
                }
                string xlhList = "";
                for (int i = 0; i < ds.Tables["v_xlh"].DefaultView.Count; i++)
                {
                    if (i > 0) xlhList += ",";
                    xlhList += "'" + ds.Tables["v_xlh"].DefaultView[i]["cInvSN"].ToString() + "'";
                }
                DataSet stds = new DataSet();
                //DataTableName dtnsn = new DataTableName();
                //dtnsn.strTableName=
                string insql = "select * from " + strYongYouDBName + ".dbo.ST_SNState with (nolock) where cInvSN in (" + xlhList + ")";
                stds = CustomizableDesignBLL.GetData(insql);
                for (int i = 0; i < ds.Tables["v_xlh"].DefaultView.Count; i++)
                {
                    bool flags = false;
                    for (int j = 0; j < stds.Tables[0].DefaultView.Count; j++)
                    {
                        if (ds.Tables["v_xlh"].DefaultView[i]["cInvSN"].ToString() == stds.Tables[0].DefaultView[j]["cInvSN"].ToString())
                        {
                            flags = true;

                            break;
                        }
                    }
                    if (!flags)
                    {
                        insql = "insert into " + strYongYouDBName + ".dbo.ST_SNState(cInvCode,cInvSN,cBatch,cwhcode,iSNState)values('" + ds.Tables["v_xlh"].DefaultView[i]["cInvCode"].ToString() + "','" + ds.Tables["v_xlh"].DefaultView[i]["cInvSN"].ToString() + "','" + ds.Tables["v_xlh"].DefaultView[i]["Define33"].ToString() + "','" + cWhCode + "',1)";

                        //objADO = null;
                        //iOptions = 0;
                        //oCon.Execute(insql, out objADO, iOptions);
                        string strPath = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Content/") + "log_in" + DateTime.Now.ToString("yyyyMMdd") + ".ini");
                        new YYAPI.Log().LogWrite(strPath, "日志入库" + DateTime.Now.ToString() + "：" + insql);

                    }
                    else
                    {
                        insql = "update " + strYongYouDBName + ".dbo.ST_SNState set cwhcode='" + cWhCode + "',cBatch='" + ds.Tables["v_xlh"].DefaultView[i]["Define33"].ToString() + "',iSNState=1 where cInvSN='" + ds.Tables["v_xlh"].DefaultView[i]["cInvSN"].ToString() + "'";

                        //objADO = null;
                        //iOptions = 0;
                        //oCon.Execute(insql, out objADO, iOptions);
                        string strPath = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Content/") + "log_in" + DateTime.Now.ToString("yyyyMMdd") + ".ini");
                        new YYAPI.Log().LogWrite(strPath, "日志入库" + DateTime.Now.ToString() + "：" + insql);

                    }
                    CustomizableDesignBLL.ExecSQL(insql);
                }
                strMsg = new YYAPI.coapi().ToYYCGRK_Audit(oCon, strID, strutfs1, strYongYouDBName, strZT, sYear, strUserCode, strUserPwd, sDate, sServer);
                if (!string.IsNullOrEmpty(strMsg))
                {
                    //oCon.RollbackTrans();

                    dt = new DataTableName();
                    dt.strExecSQL = "insert into t_cgrklog values( '" + DateTime.Now.ToString() + "','" + strID + "','','" + strMsg + "')";
                    CustomizableDesignBLL.ExecSQL(dt);

                    damResult.message = "调用审核API错误：" + strMsg;
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
                }

                string upsql = "update " + strYongYouDBName + ".dbo.ST_SNState set iSNState=2,iSNOperateCount=2 where cInvSN in (" + xlhList + ")";
                CustomizableDesignBLL.ExecSQL(upsql);
                //objADO = null;
                //iOptions = 0;
                //oCon.Execute(upsql, out objADO, iOptions);
                //
                //upsql = "update ST_SNDetail_PROIN set iSNPreState=13,iSNOperateCount=2,cSNDefine1=impoids where cInvSN in (" + xlhList + ")";
                //objADO = null;
                //iOptions = 0;
                //oCon.Execute(upsql, out objADO, iOptions);
                //
                upsql = "update " + strYongYouDBName + ".dbo.ST_SNDetail_PUIN set iSNPreState=0,iSNOperateCount=2 where cInvSN in (" + xlhList + ")";
                CustomizableDesignBLL.ExecSQL(upsql);
                //objADO = null;
                //iOptions = 0;
                //oCon.Execute(upsql, out objADO, iOptions);

                //upsql = "update mom_SNDetail set iSNCurState=13,bused=1 where cInvSN in (" + xlhList + ")";
                //objADO = null;
                //iOptions = 0;
                //oCon.Execute(upsql, out objADO, iOptions);
                //
                //string sql = "update " + strZ8DataBase + ".dbo.T_dispatch_serialno set zzBG='已入库' where OrderSerialID in(" + xlhList + ")";
                //objADO = null;
                //iOptions = 0;
                //oCon.Execute(sql, out objADO, iOptions);
                ////
                //sql = "update " + strZ8DataBase + ".dbo.T_GXbg set State=1 where SerialNum='" + strPKValue + "'";
                //objADO = null;
                //iOptions = 0;
                //oCon.Execute(sql, out objADO, iOptions);
                ////
                //sql = "update " + strZ8DataBase + ".dbo.T_GXbgDetail set State=1 where XLCode in(" + xlhList + ")";
                //objADO = null;
                //iOptions = 0;
                //oCon.Execute(sql, out objADO, iOptions);
                //
                //oCon.CommitTrans();
                //string upsql = "update " + strYongYouDBName + ".dbo.ST_SNState set iSNState=2 where cInvSN in (" + xlhList + ")";
                //string sql = "update T_dispatch_serialno set zzBG='已入库' where OrderSerialID in(" + xlhList + ")";
                //List<string> strlist = new List<string>();
                //strlist.Add(upsql);
                //strlist.Add(sql);
                //strlist.Add("update T_GXbg set State=1 where SerialNum='" + strPKValue + "'");
                //strlist.Add("update T_GXbgDetail set State=1 where XLCode in(" + xlhList + ")");
                //try
                //{
                //    CustomizableDesignBLL.ExecSQL(strlist);
                //}
                //catch (Exception ex)
                //{
                //    damResult.message = "回刷数据失败：" + ex.Message;
                //    jsonResult = JsonConvert.SerializeObject(damResult);
                //    return jsonResult;
                //}
            }
            catch (Exception ex)
            {
                //oCon.RollbackTrans();

                DataTableName dt = new DataTableName();
                dt.strExecSQL = "insert into t_cgrklog values( '" + DateTime.Now.ToString() + "','','" + tm + "','" + ex.Message + "')";
                CustomizableDesignBLL.ExecSQL(dt);

                damResult.message = "保存出错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }


            damResult.success = true;
            damResult.message = "";
            jsonResult = JsonConvert.SerializeObject(damResult);
            return jsonResult;
        }

        public string GetInInfo(string XLCode)
        {
            string jsonResult = string.Empty;
            //构造反馈对象
            dynamic damResult = new ExpandoObject();
            damResult.success = false;
            damResult.message = "获取失败";
            DataSet dsDetail = new DataSet();
            DataSet ds = new DataSet();
            string SQL = "";
            try
            {
                SQL = "select * from T_GXbgDetail where XLCode='" + XLCode + "'";
                dsDetail = CustomizableDesignBLL.GetData(SQL);
            }
            catch (Exception ex)
            {
                damResult.message = "获取信息报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            if (dsDetail.Tables[0].DefaultView.Count == 0)
            {
                damResult.message = "此序列号不存在或者未报工";
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            SQL = "select * from " + Common.GetdatabaseName("") + ".dbo.ST_SNDetail_proin where cInvSN='" + XLCode + "'";
            DataSet ddss = new DataSet();
            try
            {
                ddss = CustomizableDesignBLL.GetData(SQL);
            }
            catch (Exception ex)
            {
                damResult.message = "获取信息报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            if (ddss.Tables[0].DefaultView.Count > 0)
            {
                damResult.message = "此序列号已入库";
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            string SerialNum = dsDetail.Tables[0].DefaultView[0]["SerialNum"].ToString();
            List<DataTableName> dtnlist = new List<DataTableName>();
            DataTableName dtn = new DataTableName();
            dtn.strSelectSQL = "select * from T_GXbg where SerialNum='" + SerialNum + "'";
            dtn.strTableName = "T_GXbg";
            dtnlist.Add(dtn);
            dtn = new DataTableName();
            dtn.strSelectSQL = "select * from T_GXbgDetail where XLCode='" + XLCode + "'";
            dtn.strTableName = "T_GXbgDetail";
            dtnlist.Add(dtn);
            try
            {
                ds = CustomizableDesignBLL.GetData(dtnlist, false);
            }
            catch (Exception ex)
            {
                damResult.message = "数据获取失败" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            List<dynamic> varList = new List<dynamic>();
            List<dynamic> varListDetail = new List<dynamic>();
            if (ds.Tables[1].DefaultView.Count > 0)
            {
                foreach (DataRowView drv in ds.Tables[0].DefaultView)
                {
                    var item = Trade.DBUtility.ExtendObject.AutoMap(drv.Row);
                    varList.Add(item);
                }
                foreach (DataRowView drv in ds.Tables[1].DefaultView)
                {
                    var item = Trade.DBUtility.ExtendObject.AutoMap(drv.Row);
                    varListDetail.Add(item);
                }
                damResult.success = true;
                damResult.message = SerialNum;
                damResult.data = varList;
                damResult.Fdata = varListDetail;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            jsonResult = "{\"success\":false   ,\"message\":\"此序列号已入库！\"}";
            return jsonResult;
        }
        public string GetJHCode(string XLCode)
        {
            string jsonResult = string.Empty;
            //构造反馈对象
            dynamic damResult = new ExpandoObject();
            damResult.success = false;
            damResult.message = "获取失败";

            DataSet ds = new DataSet();
            List<DataTableName> dtnList = new List<DataTableName>();
            DataTableName dtn = new DataTableName();
            dtn.strSelectSQL = "Select * from t_jhuo where SerialNum='" + XLCode + "'  and  State=0  ";
            dtn.strTableName = "t_jhuo";
            dtnList.Add(dtn);
            dtn = new DataTableName();
            dtn.strSelectSQL = "Select * from t_jhuo_b where SerialNum='" + XLCode + "'  and  State=0";
            dtn.strTableName = "t_jhuo_b";
            dtnList.Add(dtn);
            try
            {
                ds = CustomizableDesignBLL.GetData(dtnList, false);
            }
            catch (Exception ex)
            {
                damResult.message = "获取拣货数据报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            List<dynamic> varList = new List<dynamic>();
            List<dynamic> varListDetail = new List<dynamic>();
            if (ds.Tables[0].DefaultView.Count > 0)
            {
                foreach (DataRowView drv in ds.Tables[0].DefaultView)
                {
                    var item = Trade.DBUtility.ExtendObject.AutoMap(drv.Row);
                    varList.Add(item);
                }
                foreach (DataRowView drv in ds.Tables[1].DefaultView)
                {
                    var item = Trade.DBUtility.ExtendObject.AutoMap(drv.Row);
                    varListDetail.Add(item);
                }
                damResult.success = true;
                damResult.data = varList;
                damResult.Fdata = varListDetail;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            jsonResult = "{\"success\":false   ,\"message\":\"没有拣货数据或者已发货！\"}";
            return jsonResult;


        }
        public string GetBGTable(string XLCode)
        {
            string jsonResult = string.Empty;
            //构造反馈对象
            dynamic damResult = new ExpandoObject();
            damResult.success = false;
            damResult.message = "获取失败";
            if (XLCode == "")
            {
                DataSet ds = new DataSet();
                List<DataTableName> dtnList = new List<DataTableName>();
                DataTableName dtn = new DataTableName();
                dtn.strSelectSQL = "Select * from T_GXbg where SerialNum in(Select SerialNum from T_GXbgDetail where State=0)";
                dtn.strTableName = "T_GXbg";
                dtnList.Add(dtn);
                dtn = new DataTableName();
                dtn.strSelectSQL = "Select * from T_GXbgDetail where State=0";
                dtn.strTableName = "T_GXbgDetail";
                dtnList.Add(dtn);
                try
                {
                    ds = CustomizableDesignBLL.GetData(dtnList, false);
                }
                catch (Exception ex)
                {
                    damResult.message = "获取报工数据报错：" + ex.Message;
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
                }
                List<dynamic> varList = new List<dynamic>();
                List<dynamic> varListDetail = new List<dynamic>();
                if (ds.Tables[0].DefaultView.Count > 0)
                {
                    foreach (DataRowView drv in ds.Tables[0].DefaultView)
                    {
                        var item = Trade.DBUtility.ExtendObject.AutoMap(drv.Row);
                        varList.Add(item);
                    }
                    foreach (DataRowView drv in ds.Tables[1].DefaultView)
                    {
                        var item = Trade.DBUtility.ExtendObject.AutoMap(drv.Row);
                        varListDetail.Add(item);
                    }
                    damResult.success = true;
                    damResult.data = varList;
                    damResult.Fdata = varListDetail;
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
                }
                jsonResult = "{\"success\":false   ,\"message\":\"没有报工数据！\"}";
                return jsonResult;
            }
            else
            {
                DataSet dsDetail = new DataSet();
                DataSet ds = new DataSet();
                string SQL = "select * from T_GXbgDetail where XLCode='" + XLCode + "'";
                try
                {
                    dsDetail = CustomizableDesignBLL.GetData(SQL);
                }
                catch (Exception ex)
                {
                    damResult.message = "获取信息报错：" + ex.Message;
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
                }
                if (dsDetail.Tables[0].DefaultView.Count == 0)
                {
                    damResult.message = "此序列号不存在或者未报工";
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
                }
                string SerialNum = dsDetail.Tables[0].DefaultView[0]["SerialNum"].ToString();
                List<DataTableName> dtnlist = new List<DataTableName>();
                DataTableName dtn = new DataTableName();
                dtn.strSelectSQL = "select * from T_GXbg where SerialNum='" + SerialNum + "' and State=0";
                dtn.strTableName = "T_GXbg";
                dtnlist.Add(dtn);
                dtn = new DataTableName();
                dtn.strSelectSQL = "select * from T_GXbgDetail where SerialNum='" + SerialNum + "'";
                dtn.strTableName = "T_GXbgDetail";
                dtnlist.Add(dtn);
                try
                {
                    ds = CustomizableDesignBLL.GetData(dtnlist, false);
                }
                catch (Exception ex)
                {
                    damResult.message = "数据获取失败" + ex.Message;
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
                }
                List<dynamic> varList = new List<dynamic>();
                List<dynamic> varListDetail = new List<dynamic>();
                if (ds.Tables[0].DefaultView.Count > 0)
                {
                    foreach (DataRowView drv in ds.Tables[0].DefaultView)
                    {
                        var item = Trade.DBUtility.ExtendObject.AutoMap(drv.Row);
                        varList.Add(item);
                    }
                    foreach (DataRowView drv in ds.Tables[1].DefaultView)
                    {
                        var item = Trade.DBUtility.ExtendObject.AutoMap(drv.Row);
                        varListDetail.Add(item);
                    }
                    damResult.success = true;
                    damResult.data = varList;
                    damResult.Fdata = varListDetail;
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
                }
                jsonResult = "{\"success\":false   ,\"message\":\"此序列号已入库！\"}";
                return jsonResult;
            }
        }
        public string UserLogin(string UserName, string Pwd)
        {
            string jsonResult = string.Empty;
            //构造反馈对象
            dynamic damResult = new ExpandoObject();
            damResult.success = false;
            damResult.message = "获取失败";
            YYAPI.YongYouAPI YYAPI = new YYAPI.YongYouAPI();
            string strYongYouDBName = Common.GetdatabaseName("");
            string sSubId = "AS";
            string strZT = strYongYouDBName.Substring(7, 3);
            string sAccID = strZT;
            DateTime dtCreateDate = DateTime.Now;
            string sYear = dtCreateDate.ToString("yyyy");
            //
            string sUserID = UserName;
            string sPassword = Pwd;
            string sDate = dtCreateDate.ToString("yyyy-MM-dd");
            string sServer = Common.getU8SerVerIP();// strServer; 
            string sSerial = "";
            //
            string strRet = YYAPI.u8Login(sSubId, sAccID, sYear, sUserID, sPassword, sDate, sServer, sSerial);

            //new YYAPI.Log().LogWrite(strPath, "日志2："); 
            if (strRet != string.Empty)
            {
                damResult.message = strRet;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            damResult.success = true;
            damResult.message = "正常";
            jsonResult = JsonConvert.SerializeObject(damResult);
            return jsonResult;
        }


        //dj调拨
        public string getDBList()
        {
            string jsonResult = string.Empty;
            //构造反馈对象
            dynamic damResult = new ExpandoObject();
            damResult.success = false;
            damResult.message = "获取失败";
            DataSet ds = new DataSet();
            string sql = "";
            sql = "select *,CONVERT(varchar(100), dTVDate , 23)ddatex from " + Common.GetdatabaseName("") + ".dbo.TransRequestM where  id in (select id FROM " + Common.GetdatabaseName("") + ".dbo.ST_AppTransVouchs WHERE isnull(iTvSumQuantity,0)<>iTVQuantity) " +
            "order by dTVDate desc";
            try
            {
                ds = CustomizableDesignBLL.GetData(sql);
            }
            catch (Exception ex)
            {
                damResult.message = "查询失败" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            if (ds.Tables[0].DefaultView.Count == 0)
            {
                damResult.message = "暂无调拨任务";
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            List<dynamic> varList = new List<dynamic>();
            foreach (DataRowView drv in ds.Tables[0].DefaultView)
            {
                var item = Trade.DBUtility.ExtendObject.AutoMap(drv.Row);
                varList.Add(item);
            }
            damResult.success = true;
            damResult.message = "正常";
            damResult.data = varList;
            jsonResult = JsonConvert.SerializeObject(damResult);
            return jsonResult;
        }
        public string getDbDetail(string ID)
        {
            string jsonResult = string.Empty;
            //构造反馈对象
            dynamic damResult = new ExpandoObject();
            damResult.success = false;
            damResult.message = "获取失败";
            DataSet ds = new DataSet();
            string sql = "";
            sql = "select a.*,b.cInvName from " + Common.GetdatabaseName("") + ".dbo.ST_AppTransVouchs a left join " + Common.GetdatabaseName("") + ".dbo.inventory b on a.cInvCode=b.cInvCode   where id='" + ID + "'";
            try
            {
                ds = CustomizableDesignBLL.GetData(sql);
            }
            catch (Exception ex)
            {
                damResult.message = "查询失败" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            if (ds.Tables[0].DefaultView.Count == 0)
            {
                damResult.message = "暂无出库任务";
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            List<dynamic> varList = new List<dynamic>();
            foreach (DataRowView drv in ds.Tables[0].DefaultView)
            {
                var item = Trade.DBUtility.ExtendObject.AutoMap(drv.Row);
                varList.Add(item);
            }
            damResult.success = true;
            damResult.data = varList;
            jsonResult = JsonConvert.SerializeObject(damResult);
            return jsonResult;
        }

        public string GetCodeInfoDB(string BarCode)
        {
            string jsonResult = string.Empty;
            //构造反馈对象
            dynamic damResult = new ExpandoObject();
            damResult.success = false;
            damResult.message = "获取失败";
            DataSet ds = new DataSet();
            string sqlcheck = "select * from " + Common.GetdatabaseName("") + ".dbo.ST_SNDetail_SaleOut where cInvSN='" + BarCode + "'";
            try
            {
                ds = CustomizableDesignBLL.GetData(sqlcheck);
            }
            catch (Exception ex)
            {
                damResult.message = "获取信息报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            if (ds.Tables[0].DefaultView.Count > 0)
            {
                damResult.message = "此序列号已出库";
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            sqlcheck = "select * from " + Common.GetdatabaseName("") + ".dbo.ST_SNState with (nolock) where iSNState=9 and cInvSN='" + BarCode + "'";
            try
            {
                ds = CustomizableDesignBLL.GetData(sqlcheck);
            }
            catch (Exception ex)
            {
                damResult.message = "获取信息报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            if (ds.Tables[0].DefaultView.Count > 0)
            {
                damResult.message = "此序列号已出库";
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            sqlcheck = "select * from " + Common.GetdatabaseName("") + ".dbo.ST_SNState with (nolock) where iSNState=2 and cInvSN='" + BarCode + "'";
            try
            {
                ds = CustomizableDesignBLL.GetData(sqlcheck);
            }
            catch (Exception ex)
            {
                damResult.message = "获取信息报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            if (ds.Tables[0].DefaultView.Count == 0)
            {
                damResult.message = "此序列号未入库";
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            string SQL = "select a.*,b.cwhcode from t_dispatch_serialno a  with (nolock) inner join " + Common.GetdatabaseName("") + ".dbo.ST_SNState b with (nolock) on a.OrderSerialID=b.cinvsn  where OrderSerialID='" + BarCode + "' and isdel=0";
            try
            {
                ds = CustomizableDesignBLL.GetData(SQL);
            }
            catch (Exception ex)
            {
                damResult.message = "获取信息报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            List<dynamic> varList = new List<dynamic>();
            if (ds.Tables[0].DefaultView.Count > 0)
            {
                DataSet ds2 = new DataSet();
                if (ds.Tables[0].DefaultView[0]["docno"].ToString() != string.Empty)
                {
                    sqlcheck = "select * from " + Common.GetdatabaseName("") + ".dbo.ST_SNDetail_PROIN where cInvSN='" + BarCode + "'";
                    try
                    {
                        ds2 = CustomizableDesignBLL.GetData(sqlcheck);
                    }
                    catch (Exception ex)
                    {
                        damResult.message = "获取信息报错：" + ex.Message;
                        jsonResult = JsonConvert.SerializeObject(damResult);
                        return jsonResult;
                    }
                    if (ds2.Tables[0].DefaultView.Count == 0)
                    {
                        damResult.message = "此序列号未入库";
                        jsonResult = JsonConvert.SerializeObject(damResult);
                        return jsonResult;
                    }
                }
                else
                {
                    sqlcheck = "select 1 from " + Common.GetdatabaseName("") + ".dbo.ST_SNDetail_PuIN where cInvSN='" + BarCode + "'union all  select 1 from " + Common.GetdatabaseName("") + ".dbo.ST_SNDetail_QC where cInvSN='" + BarCode + "' union all  select 1 from " + Common.GetdatabaseName("") + ".dbo.ST_SNDetail_OtherIN  where cInvSN='" + BarCode + "'";
                    try
                    {
                        ds2 = CustomizableDesignBLL.GetData(sqlcheck);
                    }
                    catch (Exception ex)
                    {
                        damResult.message = "获取信息报错：" + ex.Message;
                        jsonResult = JsonConvert.SerializeObject(damResult);
                        return jsonResult;
                    }
                    if (ds2.Tables[0].DefaultView.Count == 0)
                    {
                        damResult.message = "此序列号未入库";
                        jsonResult = JsonConvert.SerializeObject(damResult);
                        return jsonResult;
                    }
                }
                foreach (DataRowView drv in ds.Tables[0].DefaultView)
                {
                    var item = Trade.DBUtility.ExtendObject.AutoMap(drv.Row);
                    varList.Add(item);
                }
                string docno = ds.Tables[0].DefaultView[0]["docno"].ToString();
                string sql = "select top 1 cperson,cpersonname,cdeptcode,cdeptname from T_dispatchlist where docno='" + docno + "'";
                try
                {
                    ds = CustomizableDesignBLL.GetData(sql);
                }
                catch (Exception ex)
                {
                    damResult.message = "获取人员信息报错：" + ex.Message;
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
                }
                string userInfo = "";
                try
                {
                    userInfo = ds.Tables[0].DefaultView[0][0].ToString() + "-" + ds.Tables[0].DefaultView[0][1].ToString();
                }
                catch (Exception)
                {
                }

                damResult.success = true;
                damResult.data = varList;
                //damResult.bz = "(" + ds.Tables[0].DefaultView[0][2].ToString() + ")" + ds.Tables[0].DefaultView[0][3].ToString();
                damResult.message = userInfo;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            //jsonResult = "{\"success\":true  ,\"data\":" + JsonConvert.SerializeObject(varList) + "  ,\"message\":\"正常\"}";
            //
            jsonResult = "{\"success\":false   ,\"message\":\"此序列号不存在或者未入库！\"}";
            return jsonResult;

        }
        public string DBSave(string MasterData, string DetailData, string UserID, string Pwd)
        {
            string jsonResult = string.Empty;
            //构造反馈对象
            dynamic damResult = new ExpandoObject();
            damResult.success = false;
            damResult.message = "获取失败";
            string strPKValue = "";
            //测试直接JSON转换数据集的 这个是可以做的，但是不是需要现在做的。因为这个是整个框架都要改了。没那个时间
            //DataSet dstest = JsonConvert.DeserializeObject<DataSet>(strDsData);
            string strTableName = "t_db";
            string strTableDetail = strTableName + "_b";
            //先获取数据库数据，如果没有数据就新增
            List<DataTableName> dtnGetDataList = new List<DataTableName>();
            DataSet dsGetData = new DataSet();
            DataTableName dtnGetData = new DataTableName();
            dtnGetData.strSelectSQL = "Select * from " + strTableName + " where 1=0";
            dtnGetData.strTableName = strTableName;
            dtnGetDataList.Add(dtnGetData);
            //
            dtnGetData = new DataTableName();
            dtnGetData.strSelectSQL = "Select * from " + strTableDetail + " where 1=0 ";
            dtnGetData.strTableName = strTableDetail;
            dtnGetDataList.Add(dtnGetData);
            //
            try
            {
                dsGetData = CustomizableDesignBLL.GetData(dtnGetDataList, true);
            }
            catch (Exception ex)
            {
                damResult.message = "获取模块数据表结构失败:" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            if (dsGetData.Tables[strTableName].DefaultView.Count == 0)
            {
                dsGetData.Tables[strTableName].Rows.Add(dsGetData.Tables[0].NewRow());
            }
            //
            #region 主表部分
            JavaScriptSerializer Serializer = new JavaScriptSerializer();
            List<DataSave> ListDsData = Serializer.Deserialize<List<DataSave>>(MasterData);
            for (int i = 0; i < ListDsData.Count; i++)
            {
                DataSave dtmtsave = ListDsData[i];
                if (dsGetData.Tables[dtmtsave.TableName].Columns.Contains(dtmtsave.CoulumName))
                {


                    if (dsGetData.Tables[dtmtsave.TableName].Columns[dtmtsave.CoulumName].DataType.Name == "Boolean")
                    {
                        string strValue = dtmtsave.CoulunValue;


                        bool bisValue = false;
                        if (Boolean.TryParse(strValue, out bisValue))
                            dsGetData.Tables[dtmtsave.TableName].DefaultView[0][dtmtsave.CoulumName] = bisValue;
                        else
                        {
                            if (strValue.ToString().ToLower() == "true" || strValue.ToString().ToLower() == "1")
                                dsGetData.Tables[dtmtsave.TableName].DefaultView[0][dtmtsave.CoulumName] = true;
                            else
                                dsGetData.Tables[dtmtsave.TableName].DefaultView[0][dtmtsave.CoulumName] = false;
                        }
                    }
                    else
                    {
                        if (!dsGetData.Tables[dtmtsave.TableName].Columns[dtmtsave.CoulumName].ReadOnly)
                            dsGetData.Tables[dtmtsave.TableName].DefaultView[0][dtmtsave.CoulumName] = dtmtsave.CoulunValue;
                        //
                    }
                }
            }
            //一些必输项自动赋值
            strPKValue = DateTime.Now.ToString("yyyyMMdd") + GetMaxLs(DateTime.Now.ToString("yyyyMMdd"), strTableName, "id", 4).ToString("0000");
            if (dsGetData.Tables[strTableName].Columns.Contains("SaveTime"))
                dsGetData.Tables[strTableName].DefaultView[0]["SaveTime"] = DateTime.Now.ToString();
            dsGetData.Tables[strTableName].DefaultView[0]["id"] = strPKValue;
            dsGetData.Tables[strTableName].DefaultView[0].EndEdit();
            #endregion
            #region 细表部分
            // 先删除细表数据
            while (dsGetData.Tables[strTableDetail].DefaultView.Count > 0)
                dsGetData.Tables[strTableDetail].DefaultView[0].Delete();
            JavaScriptSerializer SerializerDetail = new JavaScriptSerializer();
            dynamic ListDsDataDetail = Serializer.Deserialize<dynamic>(DetailData);
            for (int i = 0; i < ListDsDataDetail.Length; i++)
            {
                DataRow drDetailNew = dsGetData.Tables[strTableDetail].NewRow();
                dynamic dtmtsavelist = ListDsDataDetail[i];
                foreach (dynamic dsv in dtmtsavelist)
                {
                    String strDetaliTablename = string.Empty;
                    String strDetaliCoulumName = string.Empty;
                    String strDetaliCoulunValue = string.Empty;
                    foreach (string strkey in dsv.Keys)
                    {
                        if (strkey == "TableName")
                            strDetaliTablename = dsv[strkey].ToString();
                        if (strkey == "CoulumName")
                            strDetaliCoulumName = dsv[strkey].ToString();
                        if (strkey == "CoulunValue")
                            strDetaliCoulunValue = dsv[strkey].ToString();
                    }
                    //
                    if (!dsGetData.Tables[strDetaliTablename].Columns.Contains(strDetaliCoulumName))
                        continue;
                    //
                    if (!dsGetData.Tables[strDetaliTablename].Columns[strDetaliCoulumName].ReadOnly && strDetaliCoulumName != "SortID" && strDetaliCoulumName != "ISDel")
                    {
                        if (dsGetData.Tables[strDetaliTablename].Columns.Contains(strDetaliCoulumName))
                        {
                            if (strDetaliCoulunValue == null || strDetaliCoulunValue == string.Empty)
                                continue;
                            if (dsGetData.Tables[strDetaliTablename].Columns[strDetaliCoulumName].DataType.Name == "Int32")
                            {
                                decimal dec = Convert.ToDecimal(strDetaliCoulunValue);
                                drDetailNew[strDetaliCoulumName] = Convert.ToInt32(dec);
                            }
                            else
                            {
                                drDetailNew[strDetaliCoulumName] = strDetaliCoulunValue;
                            }
                        }
                    }
                }
                //赋值一些必要的值
                drDetailNew["id"] = strPKValue;
                dsGetData.Tables[strTableDetail].Rows.Add(drDetailNew);
            }
            #endregion
            try
            {
                CustomizableDesignBLL.SaveData(dsGetData, dtnGetDataList);
            }
            catch (Exception ex)
            {
                damResult.message = "保存模块数据报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            #region 重新获取数据
            DataSet ds = new DataSet();
            List<DataTableName> dtnList = new List<DataTableName>();
            DataTableName dtn = new DataTableName();
            dtn.strSelectSQL = "Select * from " + strTableName + " where id= '" + strPKValue + "'";
            dtn.strTableName = strTableName;
            dtnList.Add(dtn);
            dtn = new DataTableName();
            dtn.strSelectSQL = "Select * from " + strTableDetail + " where id= '" + strPKValue + "' ";
            dtn.strTableName = strTableDetail;
            dtnList.Add(dtn);
            dtn = new DataTableName();
            dtn.strSelectSQL = "select cinvcode,cBatch,dbid,dbbid,sum(qty)qty from " + strTableDetail + " where id='" + strPKValue + "' group by cinvcode,cBatch,dbid,dbbid";
            dtn.strTableName = "t_dbhz";
            dtnList.Add(dtn);
            try
            {
                ds = CustomizableDesignBLL.GetData(dtnList, false);
            }
            catch (Exception ex)
            {
                damResult.message = "获取保存后数据报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            #endregion
            string xlhList = "";
            for (int i = 0; i < ds.Tables[1].DefaultView.Count; i++)
            {
                if (i > 0) xlhList += ",";
                xlhList += "'" + ds.Tables[1].DefaultView[i]["XLCode"].ToString() + "'";
            }

            string strConn = ConfigurationManager.ConnectionStrings["ConStr1"].ConnectionString;
            ADODB.Connection oCon = new ADODB.Connection();
            string strZ8DataBase = ConfigurationManager.AppSettings["Z8DataBase"];
            if (strZ8DataBase == null || strZ8DataBase == "")
            {
                damResult.message = "Z8DataBase没有设置";
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            string strYongYouDBName = Common.GetdatabaseName("");
            string strZT = strYongYouDBName.Substring(7, 3);
            string sAccID = strZT;
            string sYear = DateTime.Now.Year.ToString();
            string strUserCode = UserID;
            string strUserPwd = Pwd;
            string sDate = DateTime.Now.ToString("yyyy-MM-dd");
            string sServer = Common.getU8SerVerIP();// "172.16.1.20";// strServerIP; 
            //if (Common.getBisTest())
            //{
            //    sDate = new DateTime(2019, 2, 28).ToString("yyyy-MM-dd");
            //}
            //
            //if (string.IsNullOrEmpty(strUserCode))
            //{
            strUserCode = "sxc";
            strUserPwd = "637813";

            //damResult.message = "strUserCode没有设置";
            //jsonResult = JsonConvert.SerializeObject(damResult);
            //return jsonResult;
            //}
            string FHID = ds.Tables[0].DefaultView[0]["dbid"].ToString();
            List<DataTableName> list = new List<DataTableName>();
            dtn = new DataTableName();
            dtn.strSelectSQL = "select * from " + strYongYouDBName + ".dbo.ST_AppTransVouch  where id='" + FHID + "'";
            dtn.strTableName = "ST_AppTransVouch";
            list.Add(dtn);
            dtn = new DataTableName();
            dtn.strSelectSQL = "select * from " + strYongYouDBName + ".dbo.ST_AppTransVouch where id='" + FHID + "'";
            dtn.strTableName = "ST_AppTransVouchs";
            list.Add(dtn);

            DataSet dsToU8 = new DataSet();
            try
            {
                oCon.CursorLocation = ADODB.CursorLocationEnum.adUseClient;
                oCon.ConnectionString = strConn;
                oCon.Open(strConn, "", "", -1);
                //开始事务，很关键
                //oCon.BeginTrans();
                dsToU8 = CustomizableDesignBLL.GetData(list, false);
                //因为要排序，所以传了ds.Copy()
                string strMsg = new YYAPI.coapi().ToYYDBD(oCon, ds.Copy(), dsToU8, strYongYouDBName, strZT, sYear, strUserCode, strUserPwd, sDate, sServer, strPKValue);
                if (!string.IsNullOrEmpty(strMsg))
                {
                    //oCon.RollbackTrans();
                    damResult.message = "调用调拨单API错误：" + strMsg;
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
                }
 
                //不用事务  直接插表 不知道为什么会卡死
                string rsql = "select (select top 1 cIWhCode  from " + strYongYouDBName + ".dbo.TransVouch where id=TransVouchs.id) cIWhCode ,(select top 1 cOWhCode   from " + strYongYouDBName + ".dbo.TransVouch where id=TransVouchs.id) cOWhCode  ,(select top 1 convert(nchar,convert(money,ufts),2) from " + strYongYouDBName + ".dbo.TransVouch where id=TransVouchs.id) utfs1,* from " + strYongYouDBName + ".dbo.TransVouchs where cdefine27='" + strPKValue + "'";
                DataSet rds = CustomizableDesignBLL.GetData(rsql);
                if (rds.Tables[0].DefaultView.Count == 0)
                {
                    damResult.message = "调拨记录为空！";
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
                }
                string strID = rds.Tables[0].DefaultView[0]["id"].ToString();
                string strutfs1 = rds.Tables[0].DefaultView[0]["utfs1"].ToString();
                for (int i = 0; i < rds.Tables[0].DefaultView.Count; i++)
                {
                    int x = 1;
                    for (int j = 0; j < ds.Tables[1].DefaultView.Count; j++)
                    {
                        if (rds.Tables[0].DefaultView[i]["iTRIds"].ToString() == ds.Tables[1].DefaultView[j]["dbid"].ToString()
                            && rds.Tables[0].DefaultView[i]["cinvcode"].ToString() == ds.Tables[1].DefaultView[j]["cinvcode"].ToString())
                        {
                            string ivouchsID = rds.Tables[0].DefaultView[i]["AutoID"].ToString();
                            string ivouchID = rds.Tables[0].DefaultView[i]["ID"].ToString();
                            string cInvCode = rds.Tables[0].DefaultView[i]["cInvCode"].ToString();
                            string coutWhCode = rds.Tables[0].DefaultView[i]["coWhCode"].ToString();
                            string cinWhCode = rds.Tables[0].DefaultView[i]["ciWhCode"].ToString();                      
                            string iRowNo = x.ToString();
                            string cInvSN = ds.Tables[1].DefaultView[j]["XLCode"].ToString();
                            string cBatch = ds.Tables[1].DefaultView[j]["cBatch"].ToString();
                            x++;
                            string sqlinxl = "insert into " + strYongYouDBName + ".dbo.ST_SNDetail_Tran(ivouchsID,ivouchID,irowno,cInvCode,coutWhCode,cinWhCode,iSNPreState,iSNOperateCount,cBatch,cInvSN,cprewhcode,cpreBatch) " +
                                 "Values(" + ivouchsID + "," + ivouchID + ",'" + iRowNo + "','" + cInvCode + "','" + coutWhCode + "','" + cinWhCode + "',2,3,'" + cBatch + "','" + cInvSN + "','" + coutWhCode + "','" + cBatch + "')";
                            CustomizableDesignBLL.ExecSQL(sqlinxl);
                        }
                    }
                }
                DataSet stds = new DataSet();
                string insql = "select * from " + strYongYouDBName + ".dbo.ST_SNState with (nolock) where cInvSN in (" + xlhList + ")";
                stds = CustomizableDesignBLL.GetData(insql);

                for (int i = 0; i < ds.Tables[1].DefaultView.Count; i++)
                {
                    bool flags = false;
                    insql = "update " + strYongYouDBName + ".dbo.ST_SNState set iSNOperateCount=3,iSNState=3 where cInvSN='" + ds.Tables[1].DefaultView[i]["XLCode"].ToString() + "'";
                    CustomizableDesignBLL.ExecSQL(insql);
                    string strPath = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Content/") + "log_out" + DateTime.Now.ToString("yyyyMMdd") + ".ini");
                    new YYAPI.Log().LogWrite(strPath, "日志出库" + DateTime.Now.ToString() + "：" + insql);
                }
                strMsg = new YYAPI.coapi().ToYYDBD_Audit(oCon, strID, strutfs1, strYongYouDBName, strZT, sYear, strUserCode, strUserPwd, sDate, sServer);
                if (!string.IsNullOrEmpty(strMsg))
                {
    
                    damResult.message = "调用审核API错误：" + strMsg;
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
               }
                //审核其他出入库单

                string rdsql = "select isnull(chandler,'')chandler,id, convert(nchar,convert(money,ufts),2)utfs1 from  " + strYongYouDBName + ".dbo.rdrecord09 where cdefine10='" + strPKValue + "'";
                DataSet rdds = CustomizableDesignBLL.GetData(rdsql);
                if (rdds.Tables[0].DefaultView.Count > 0) {
                    string chandler = rdds.Tables[0].DefaultView[0]["chandler"].ToString();
                    if (string.IsNullOrEmpty(chandler)) {
                        new YYAPI.coapi().ToYYQTCK_Audit(oCon, rdds.Tables[0].DefaultView[0]["id"].ToString(), rdds.Tables[0].DefaultView[0]["utfs1"].ToString(), strYongYouDBName, strZT, sYear, strUserCode, strUserPwd, sDate, sServer);
                    }
                }
                rdsql = "select isnull(chandler,'')chandler,id, convert(nchar,convert(money,ufts),2)utfs1 from  " + strYongYouDBName + ".dbo.rdrecord08 where cdefine10='" + strPKValue + "'";
                rdds = CustomizableDesignBLL.GetData(rdsql);
                if (rdds.Tables[0].DefaultView.Count > 0)
                {
                    string chandler = rdds.Tables[0].DefaultView[0]["chandler"].ToString();
                    if (string.IsNullOrEmpty(chandler))
                    {
                        new YYAPI.coapi().ToYYQTRK_Audit(oCon, rdds.Tables[0].DefaultView[0]["id"].ToString(), rdds.Tables[0].DefaultView[0]["utfs1"].ToString(), strYongYouDBName, strZT, sYear, strUserCode, strUserPwd, sDate, sServer);
                    }
                }

            }
            catch (Exception ex)
            {
                damResult.message = "错误：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            damResult.success = true;
            damResult.message = "";
            jsonResult = JsonConvert.SerializeObject(damResult);
            return jsonResult;
        }




        //////////////////////////////////////////
        public string SaveInTest()
        {
            string UserID = "wm";
            string Pwd = "wm001";
            string strPKValue = "202009010237";
            string swList = "";
            //
            string jsonResult = string.Empty;
            //构造反馈对象
            dynamic damResult = new ExpandoObject();
            damResult.success = false;
            damResult.message = "获取失败";
            string strTableName = "T_GXbg";
            string strTableDetail = "T_GXbgDetail";
            string strPKValues = "";
            #region 重新获取数据
            DataSet ds = new DataSet();
            List<DataTableName> dtnList = new List<DataTableName>();
            DataTableName dtn = new DataTableName();
            dtn.strSelectSQL = "Select * from " + strTableName + " where SerialNum= '" + strPKValue + "'";
            dtn.strTableName = strTableName;
            dtnList.Add(dtn);
            dtn = new DataTableName();
            if (swList != "")
                dtn.strSelectSQL = "Select * from " + strTableDetail + " where SerialNum= '" + strPKValue + "' and XLCode in(" + swList + ")";
            else
                dtn.strSelectSQL = "Select * from " + strTableDetail + " where SerialNum= '" + strPKValue + "'";
            dtn.strTableName = strTableDetail;
            dtnList.Add(dtn);
            try
            {
                ds = CustomizableDesignBLL.GetData(dtnList, false);
            }
            catch (Exception ex)
            {
                damResult.message = "获取保存后数据报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            #endregion

            string strConn = ConfigurationManager.ConnectionStrings["ConStr1"].ConnectionString;
            ADODB.Connection oCon = new ADODB.Connection();
            string strZ8DataBase = ConfigurationManager.AppSettings["Z8DataBase"];
            if (strZ8DataBase == null || strZ8DataBase == "")
            {
                damResult.message = "Z8DataBase没有设置";
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            string strYongYouDBName = Common.GetdatabaseName("");
            string strZT = strYongYouDBName.Substring(7, 3);
            string sAccID = strZT;
            string sYear = DateTime.Now.Year.ToString();
            string strUserCode = UserID;
            string strUserPwd = Pwd;
            string sDate = DateTime.Now.ToString("yyyy-MM-dd");
            string sServer = Common.getU8SerVerIP();// "172.16.1.20";// strServerIP; 
            //if (Common.getBisTest())
            //{
            //    sDate = new DateTime(2019, 2, 28).ToString("yyyy-MM-dd");
            //}
            //
            //合并中间表
            #region 合并相同存货的数量
            ds.Tables[1].DefaultView.Sort = "MoDID";
            DataSet dsff = ds.Clone();
            int len = ds.Tables[1].DefaultView.Count;
            decimal qty = 0;
            string Modid = "";
            bool flag = false;
            for (int i = 0; i < len; )
            {
                flag = true;
                bool xx = false;//是否进入以下循环
                qty = decimal.Parse(ds.Tables[1].DefaultView[i]["qty"].ToString()); ;
                Modid = ds.Tables[1].DefaultView[i]["Modid"].ToString();
                for (int j = i + 1; j < len; j++)
                {
                    xx = true;
                    if (Modid == ds.Tables[1].DefaultView[j]["Modid"].ToString())
                    {
                        qty += 1;
                        ds.Tables[1].DefaultView[j]["qty"] = qty;
                        i = j;
                    }
                    else
                    {
                        flag = false;
                        ds.Tables[1].DefaultView[i]["qty"] = qty;
                        ds.Tables[1].DefaultView[i].EndEdit();
                        dsff.Tables[1].Rows.Add(ds.Tables[1].DefaultView[i].Row.ItemArray);
                        i = j;
                        break;
                    }

                }
                if (!xx) i++;
            }
            if (flag)
            {
                ds.Tables[1].DefaultView[len - 1]["qty"] = qty;
                ds.Tables[1].DefaultView[len - 1].EndEdit();
                dsff.Tables[1].Rows.Add(ds.Tables[1].DefaultView[len - 1].Row.ItemArray);
            }
            dsff.Tables[0].Rows.Add(ds.Tables[0].DefaultView[0].Row.ItemArray);
            for (int w = 0; w < dsff.Tables[1].DefaultView.Count; w++)
            {
                if (strPKValues != "") strPKValues += ",";
                strPKValues += "'" + dsff.Tables[1].DefaultView[w]["SerialID"].ToString() + "'";
            }
            #endregion

            //检验是否已生成入库单
            string sqlcin = "select * from " + strYongYouDBName + ".dbo.rdrecord10 where cdefine10='" + dsff.Tables[1].DefaultView[0]["SerialID"].ToString() + "'";
            try
            {
                DataSet sqlds = CustomizableDesignBLL.GetData(sqlcin);
                if (sqlds.Tables[0].DefaultView.Count > 0)
                {
                    damResult.message = "已经生成此单据的入库单,请前往U8处理,单号为" + sqlds.Tables[0].DefaultView[0]["cCode"].ToString();
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
                }
            }
            catch (Exception ex)
            {
                damResult.message = "sql有误" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            try
            {
                oCon.CursorLocation = ADODB.CursorLocationEnum.adUseClient;
                oCon.ConnectionString = strConn;
                oCon.Open(strConn, "", "", -1);
                //开始事务，很关键
                oCon.BeginTrans();
                //因为要排序，所以传了ds.Copy()
                string strMsg = new YYAPI.YongYouAPI().ProductInstorage(oCon, dsff.Copy(), strYongYouDBName, strZT, sYear, strUserCode, strUserPwd, sDate, sServer, strPKValue);
                if (!string.IsNullOrEmpty(strMsg))
                {
                    oCon.RollbackTrans();
                    damResult.message = "调用产成品入库API错误：" + strMsg;
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
                }

                ADODB.Recordset rsRecord = new ADODB.Recordset();
                string strRsSQLRecord = "select (select top 1 cWhCode from rdrecord10 where id=rdrecords10.id) cWhCode,(select top 1 convert(nchar,convert(money,ufts),2) from rdrecord10 where id=rdrecords10.id) utfs1,* from rdrecords10 where cdefine25 in(" + strPKValues + ")";
                rsRecord.Open(strRsSQLRecord, oCon, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockOptimistic, (int)ADODB.CommandTypeEnum.adCmdText);
                object objADO = null;
                int iOptions = 0;
                if (rsRecord.RecordCount == 0)
                {
                    oCon.RollbackTrans();
                    damResult.message = "出库记录为空！";
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
                }
                string strID = rsRecord.Fields["id"].Value.ToString();
                string strutfs1 = rsRecord.Fields["utfs1"].Value.ToString();
                for (int i = 0; i < rsRecord.RecordCount; i++)
                {
                    int x = 1;
                    for (int j = 0; j < ds.Tables[1].DefaultView.Count; j++)
                    {
                        if (rsRecord.Fields["impoids"].Value.ToString() == ds.Tables[1].DefaultView[j]["MoDID"].ToString())
                        {
                            string ivouchsID = rsRecord.Fields["AutoID"].Value.ToString();
                            string ivouchID = rsRecord.Fields["ID"].Value.ToString();
                            string cInvCode = rsRecord.Fields["cInvCode"].Value.ToString();
                            string cWhCode = rsRecord.Fields["cWhCode"].Value.ToString();
                            string impoids = rsRecord.Fields["impoids"].Value.ToString();
                            string iRowNo = x.ToString();
                            string cInvSN = ds.Tables[1].DefaultView[j]["XLCode"].ToString();
                            string cBatch = rsRecord.Fields["cBatch"].Value.ToString();
                            x++;
                            string sqlinxl = "insert into ST_SNDetail_PROIN(ivouchsID,ivouchID,cInvCode,cWhCode,impoids,csource,iSNPreState,iRowNo,cInvSN,cBatch) " +
                               "Values(" + ivouchsID + "," + ivouchID + ",'" + cInvCode + "','" + cWhCode + "'," + impoids + ",'生产订单',0," + iRowNo + ",'" + cInvSN + "','" + cBatch + "')";
                            objADO = null;
                            iOptions = 0;
                            oCon.Execute(sqlinxl, out objADO, iOptions);
                            //判断cInvSN>1
                            ADODB.Recordset rs = new ADODB.Recordset();
                            string strRsSQL = "SELECT * FROM ST_SNDetail_PROIN WHERE cInvSN='" + cInvSN + "'";
                            rs.Open(strRsSQL, oCon, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockOptimistic, (int)ADODB.CommandTypeEnum.adCmdText);
                            if (rs.RecordCount > 1)
                            {
                                oCon.RollbackTrans();
                                damResult.message = "序列号:" + cInvSN + "重复";
                                jsonResult = JsonConvert.SerializeObject(damResult);
                                return jsonResult;
                            }
                        }
                    }
                    rsRecord.MoveNext();
                }
                string xlhList = "";
                for (int i = 0; i < ds.Tables[1].DefaultView.Count; i++)
                {
                    if (i > 0) xlhList += ",";
                    xlhList += "'" + ds.Tables[1].DefaultView[i]["XLCode"].ToString() + "'";
                }
                DataSet stds = new DataSet();
                //DataTableName dtnsn = new DataTableName();
                //dtnsn.strTableName=
                string insql = "select * from " + strYongYouDBName + ".dbo.ST_SNState with (nolock) where cInvSN in (" + xlhList + ")";
                stds = CustomizableDesignBLL.GetData(insql);
                for (int i = 0; i < ds.Tables[1].DefaultView.Count; i++)
                {
                    bool flags = false;
                    for (int j = 0; j < stds.Tables[0].DefaultView.Count; j++)
                    {
                        if (ds.Tables[1].DefaultView[i]["XLCode"].ToString() == stds.Tables[0].DefaultView[j]["cInvSN"].ToString())
                        {
                            flags = true;

                            break;
                        }
                    }
                    if (!flags)
                    {
                        insql = "insert into " + strYongYouDBName + ".dbo.ST_SNState(cInvCode,cInvSN,cBatch,cwhcode,iSNState)values('" + ds.Tables[1].DefaultView[i]["cInvCode"].ToString() + "','" + ds.Tables[1].DefaultView[i]["XLCode"].ToString() + "','" + ds.Tables[1].DefaultView[i]["cBatch"].ToString() + "','" + ds.Tables[0].DefaultView[0]["cWhCode"].ToString() + "',1)";

                        objADO = null;
                        iOptions = 0;
                        oCon.Execute(insql, out objADO, iOptions);
                        string strPath = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Content/") + "log_in" + DateTime.Now.ToString("yyyyMMdd") + ".ini");
                        new YYAPI.Log().LogWrite(strPath, "日志入库" + DateTime.Now.ToString() + "：" + insql);

                    }
                    else
                    {
                        insql = "update " + strYongYouDBName + ".dbo.ST_SNState set cwhcode='" + ds.Tables[0].DefaultView[0]["cWhCode"].ToString() + "',cBatch='" + ds.Tables[1].DefaultView[i]["cBatch"].ToString() + "',iSNState=1 where cInvSN='" + ds.Tables[1].DefaultView[i]["XLCode"].ToString() + "'";

                        objADO = null;
                        iOptions = 0;
                        oCon.Execute(insql, out objADO, iOptions);
                        string strPath = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Content/") + "log_in" + DateTime.Now.ToString("yyyyMMdd") + ".ini");
                        new YYAPI.Log().LogWrite(strPath, "日志入库" + DateTime.Now.ToString() + "：" + insql);

                    }
                }
                strMsg = new YYAPI.YongYouAPI().CPInStorageAudit(oCon, strID, strutfs1, strYongYouDBName, strZT, sYear, strUserCode, strUserPwd, sDate, sServer);
                if (!string.IsNullOrEmpty(strMsg))
                {
                    oCon.RollbackTrans();
                    damResult.message = "调用审核API错误：" + strMsg;
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
                }

                string upsql = "update ST_SNState set iSNState=2,iSNOperateCount=2 where cInvSN in (" + xlhList + ")";
                objADO = null;
                iOptions = 0;
                oCon.Execute(upsql, out objADO, iOptions);
                //
                upsql = "update ST_SNDetail_PROIN set iSNPreState=13,iSNOperateCount=2,cSNDefine1=impoids where cInvSN in (" + xlhList + ")";
                objADO = null;
                iOptions = 0;
                oCon.Execute(upsql, out objADO, iOptions);
                //
                upsql = "update mom_SNDetail set iSNCurState=13,bused=1 where cInvSN in (" + xlhList + ")";
                objADO = null;
                iOptions = 0;
                oCon.Execute(upsql, out objADO, iOptions);
                //
                string sql = "update " + strZ8DataBase + ".dbo.T_dispatch_serialno set zzBG='已入库' where OrderSerialID in(" + xlhList + ")";
                objADO = null;
                iOptions = 0;
                oCon.Execute(sql, out objADO, iOptions);
                //
                sql = "update " + strZ8DataBase + ".dbo.T_GXbg set State=1 where SerialNum='" + strPKValue + "'";
                objADO = null;
                iOptions = 0;
                oCon.Execute(sql, out objADO, iOptions);
                //
                sql = "update " + strZ8DataBase + ".dbo.T_GXbgDetail set State=1 where XLCode in(" + xlhList + ")";
                objADO = null;
                iOptions = 0;
                oCon.Execute(sql, out objADO, iOptions);
                //
                oCon.CommitTrans();
                //string upsql = "update " + strYongYouDBName + ".dbo.ST_SNState set iSNState=2 where cInvSN in (" + xlhList + ")";
                //string sql = "update T_dispatch_serialno set zzBG='已入库' where OrderSerialID in(" + xlhList + ")";
                //List<string> strlist = new List<string>();
                //strlist.Add(upsql);
                //strlist.Add(sql);
                //strlist.Add("update T_GXbg set State=1 where SerialNum='" + strPKValue + "'");
                //strlist.Add("update T_GXbgDetail set State=1 where XLCode in(" + xlhList + ")");
                //try
                //{
                //    CustomizableDesignBLL.ExecSQL(strlist);
                //}
                //catch (Exception ex)
                //{
                //    damResult.message = "回刷数据失败：" + ex.Message;
                //    jsonResult = JsonConvert.SerializeObject(damResult);
                //    return jsonResult;
                //}
            }
            catch (Exception ex)
            {
                oCon.RollbackTrans();
                damResult.message = "保存出错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }


            damResult.success = true;
            damResult.message = "";
            jsonResult = JsonConvert.SerializeObject(damResult);
            return jsonResult;
        }

        public string CKSaveTest()
        {
            string jsonResult = string.Empty;
            //构造反馈对象
            dynamic damResult = new ExpandoObject();
            damResult.success = false;
            damResult.message = "获取失败";
            string strPKValue = "202009090001";
            //测试直接JSON转换数据集的 这个是可以做的，但是不是需要现在做的。因为这个是整个框架都要改了。没那个时间
            //DataSet dstest = JsonConvert.DeserializeObject<DataSet>(strDsData);
            string strTableName = "T_CPCK";
            string strTableDetail = strTableName + "Product";
            #region 重新获取数据
            DataSet ds = new DataSet();
            List<DataTableName> dtnList = new List<DataTableName>();
            DataTableName dtn = new DataTableName();
            dtn.strSelectSQL = "Select * from " + strTableName + " where SerialNum= '" + strPKValue + "'";
            dtn.strTableName = strTableName;
            dtnList.Add(dtn);
            dtn = new DataTableName();
            dtn.strSelectSQL = "Select * from " + strTableDetail + " where SerialNum= '" + strPKValue + "' ";
            dtn.strTableName = strTableDetail;
            dtnList.Add(dtn);
            try
            {
                ds = CustomizableDesignBLL.GetData(dtnList, false);
            }
            catch (Exception ex)
            {
                damResult.message = "获取保存后数据报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            #endregion
            string xlhList = "";
            for (int i = 0; i < ds.Tables[1].DefaultView.Count; i++)
            {
                if (i > 0) xlhList += ",";
                xlhList += "'" + ds.Tables[1].DefaultView[i]["XLCode"].ToString() + "'";
            }

            string strConn = ConfigurationManager.ConnectionStrings["ConStr1"].ConnectionString;
            ADODB.Connection oCon = new ADODB.Connection();
            string strZ8DataBase = ConfigurationManager.AppSettings["Z8DataBase"];
            if (strZ8DataBase == null || strZ8DataBase == "")
            {
                damResult.message = "Z8DataBase没有设置";
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            string strYongYouDBName = Common.GetdatabaseName("");
            string strZT = "001";
            string sAccID = "001";
            string sYear = DateTime.Now.Year.ToString();
            string strUserCode = "wm";
            string strUserPwd = "wm001";
            string sDate = DateTime.Now.ToString("yyyy-MM-dd");
            string sServer = Common.getU8SerVerIP();// "172.16.1.20";// strServerIP; 
            //if (Common.getBisTest())
            //{
            //    sDate = new DateTime(2019, 2, 28).ToString("yyyy-MM-dd");
            //}
            //
            string FHID = ds.Tables[0].DefaultView[0]["FHID"].ToString();
            List<DataTableName> list = new List<DataTableName>();
            dtn = new DataTableName();
            dtn.strSelectSQL = "select * from " + strYongYouDBName + ".dbo.dispatchlist where DLID='" + FHID + "'";
            dtn.strTableName = "dispatchlist";
            list.Add(dtn);
            dtn = new DataTableName();
            dtn.strSelectSQL = "select * from " + strYongYouDBName + ".dbo.dispatchlists where DLID='" + FHID + "'";
            dtn.strTableName = "dispatchlists";
            list.Add(dtn);
            DataSet dsToU8 = new DataSet();
            try
            {
                oCon.CursorLocation = ADODB.CursorLocationEnum.adUseClient;
                oCon.ConnectionString = strConn;
                oCon.Open(strConn, "", "", -1);
                //开始事务，很关键
                oCon.BeginTrans();
                dsToU8 = CustomizableDesignBLL.GetData(list, false);
                //因为要排序，所以传了ds.Copy()
                string strMsg = new YYAPI.YongYouAPI().CPOutStorage(oCon, ds.Copy(), dsToU8, strYongYouDBName, strZT, sYear, strUserCode, strUserPwd, sDate, sServer, strPKValue);
                if (!string.IsNullOrEmpty(strMsg))
                {
                    oCon.RollbackTrans();
                    damResult.message = "调用销售出库API错误：" + strMsg;
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
                }
                ////
                //DataSet dsFromU8 = null;
                //List<DataTableName> dtnlist = new List<DataTableName>();
                //dtn = new DataTableName();
                //dtn.strSelectSQL = "select *,convert(nchar,convert(money,ufts),2) as ufts1 from " + strYongYouDBName + ".dbo.rdrecord32 where cdefine10='" + strPKValue + "'";
                //dtn.strTableName = "rdrecord32";
                //dtnlist.Add(dtn);
                //dtn = new DataTableName();
                //dtn.strSelectSQL = "select * from " + strYongYouDBName + ".dbo.rdrecords32 where cdefine27='" + strPKValue + "'";
                //dtn.strTableName = "rdrecords32";
                //dtnlist.Add(dtn);
                //try
                //{
                //    dsFromU8 = CustomizableDesignBLL.GetData(dtnlist, false);
                //}
                //catch (Exception ex)
                //{
                //    oCon.RollbackTrans();
                //    damResult.message = ("取U8产成品入库单出错：" + ex.Message);
                //    jsonResult = JsonConvert.SerializeObject(damResult);
                //    return jsonResult;
                //}
                ADODB.Recordset rsRecord = new ADODB.Recordset();
                string strRsSQLRecord = "select (select top 1 cWhCode from rdrecord32 where id=rdrecords32.id) cWhCode,(select top 1 convert(nchar,convert(money,ufts),2) from rdrecord32 where id=rdrecords32.id) utfs1,* from rdrecords32 where cdefine27='" + strPKValue + "'";
                rsRecord.Open(strRsSQLRecord, oCon, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockOptimistic, (int)ADODB.CommandTypeEnum.adCmdText);
                object objADO = null;
                int iOptions = 0;
                if (rsRecord.RecordCount == 0)
                {
                    oCon.RollbackTrans();
                    damResult.message = "出库记录为空！";
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
                }
                string strID = rsRecord.Fields["id"].Value.ToString();
                string strutfs1 = rsRecord.Fields["utfs1"].Value.ToString();
                for (int i = 0; i < rsRecord.RecordCount; i++)
                {
                    int x = 1;
                    for (int j = 0; j < ds.Tables[1].DefaultView.Count; j++)
                    {
                        if (rsRecord.Fields["idlsid"].Value.ToString() == ds.Tables[1].DefaultView[j]["FHDID"].ToString())
                        {
                            string ivouchsID = rsRecord.Fields["AutoID"].Value.ToString();
                            string ivouchID = rsRecord.Fields["ID"].Value.ToString();
                            string cInvCode = rsRecord.Fields["cInvCode"].Value.ToString();
                            string cWhCode = rsRecord.Fields["cWhCode"].Value.ToString();
                            string idlsid = rsRecord.Fields["idlsid"].Value.ToString();
                            string iRowNo = x.ToString();
                            string cInvSN = ds.Tables[1].DefaultView[j]["XLCode"].ToString();
                            string cBatch = rsRecord.Fields["cBatch"].Value.ToString();
                            x++;
                            string sqlinxl = "insert into ST_SNDetail_SaleOut(ivouchsID,ivouchID,cInvCode,cWhCode,idlsid,csource,iSNPreState,iRowNo,cInvSN,cBatch,cprewhcode,cpreBatch) " +
                                "Values(" + ivouchsID + "," + ivouchID + ",'" + cInvCode + "','" + cWhCode + "'," + idlsid + ",'发货单',2," + iRowNo + ",'" + cInvSN + "','" + cBatch + "','" + cWhCode + "','" + cBatch + "')";
                            objADO = null;
                            iOptions = 0;
                            oCon.Execute(sqlinxl, out objADO, iOptions);
                            //判断cInvSN>1
                            ADODB.Recordset rs = new ADODB.Recordset();
                            string strRsSQL = "SELECT * FROM ST_SNDetail_SaleOut WHERE cInvSN='" + cInvSN + "'";
                            rs.Open(strRsSQL, oCon, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockOptimistic, (int)ADODB.CommandTypeEnum.adCmdText);
                            if (rs.RecordCount > 1)
                            {
                                oCon.RollbackTrans();
                                damResult.message = "序列号:" + cInvSN + "重复";
                                jsonResult = JsonConvert.SerializeObject(damResult);
                                return jsonResult;
                            }
                        }
                    }
                    rsRecord.MoveNext();
                }
                DataSet stds = new DataSet();
                string insql = "select * from " + strYongYouDBName + ".dbo.ST_SNState with (nolock) where cInvSN in (" + xlhList + ")";
                stds = CustomizableDesignBLL.GetData(insql);

                for (int i = 0; i < ds.Tables[1].DefaultView.Count; i++)
                {
                    bool flags = false;
                    for (int j = 0; j < stds.Tables[0].DefaultView.Count; j++)
                    {
                        if (ds.Tables[1].DefaultView[i]["XLCode"].ToString() == stds.Tables[0].DefaultView[j]["cInvSN"].ToString())
                        {
                            flags = true;
                            break;
                        }
                    }
                    if (!flags)
                    {
                        insql = "insert into " + strYongYouDBName + ".dbo.ST_SNState(cInvCode,cInvSN,cBatch,cwhcode,iSNState)values('" + ds.Tables[1].DefaultView[i]["cInvCode"].ToString() + "','" + ds.Tables[1].DefaultView[i]["XLCode"].ToString() + "','" + ds.Tables[1].DefaultView[i]["cBatch"].ToString() + "','" + ds.Tables[0].DefaultView[0]["cWhCode"].ToString() + "',3)";
                        objADO = null;
                        iOptions = 0;
                        oCon.Execute(insql, out objADO, iOptions);
                        //oCon.CommitTrans();
                        string strPath = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Content/") + "log_Out" + DateTime.Now.ToString("yyyyMMdd") + ".ini");
                        new YYAPI.Log().LogWrite(strPath, "日志出库" + DateTime.Now.ToString() + "：" + insql);
                    }
                    else
                    {
                        insql = "update " + strYongYouDBName + ".dbo.ST_SNState set cwhcode='" + ds.Tables[0].DefaultView[0]["cWhCode"].ToString() + "',cBatch='" + ds.Tables[1].DefaultView[i]["cBatch"].ToString() + "',iSNState=3 where cInvSN='" + ds.Tables[1].DefaultView[i]["XLCode"].ToString() + "'";
                        objADO = null;
                        iOptions = 0;
                        oCon.Execute(insql, out objADO, iOptions);
                        //oCon.CommitTrans();
                        string strPath = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Content/") + "log_out" + DateTime.Now.ToString("yyyyMMdd") + ".ini");
                        new YYAPI.Log().LogWrite(strPath, "日志出库" + DateTime.Now.ToString() + "：" + insql);
                    }
                }
                strMsg = new YYAPI.YongYouAPI().CPOutStorageAudit(oCon, strID, strutfs1, strYongYouDBName, strZT, sYear, strUserCode, strUserPwd, sDate, sServer);
                if (!string.IsNullOrEmpty(strMsg))
                {
                    oCon.RollbackTrans();
                    damResult.message = "调用审核API错误：" + strMsg;
                    jsonResult = JsonConvert.SerializeObject(damResult);
                    return jsonResult;
                }

                string upsql = "update " + strYongYouDBName + ".dbo.ST_SNState set iSNState=9 where cInvSN in (" + xlhList + ")";
                objADO = null;
                iOptions = 0;
                oCon.Execute(upsql, out objADO, iOptions);
                //
                string sql = "update " + strZ8DataBase + ".dbo.T_dispatch_serialno set zzBG='已出库' where OrderSerialID in(" + xlhList + ")";
                objADO = null;
                iOptions = 0;
                oCon.Execute(sql, out objADO, iOptions);
                //
                oCon.CommitTrans();
            }
            catch (Exception ex)
            {
                oCon.RollbackTrans();
                damResult.message = "错误：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            damResult.success = true;
            damResult.message = "";
            jsonResult = JsonConvert.SerializeObject(damResult);
            return jsonResult;
        }
    }
}
